Save current stylesheet to local storage

Asked by Caspian Corona on
Tags: current
10 Answers

Answer by Juliette McKee

So, here is the thing - I have two stylesheets on my site. I want to save lately used stylesheet to local storage., Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers ,Stack Overflow en español, Meta Stack Overflow

index.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
    <link id="active-stylesheet" href="" rel="stylesheet" type="text/css"/>
</head>

<body>
    <div class="switch-buttons">
        <button class="switch-buttons__light button" data-stylesheet="light.css">Go Light</button>
        <button class="switch-buttons__dark button" data-stylesheet="dark.css">Go Dark</button>
    </div>
    <h1>Light and Dark Stylesheets with Web Storage API</h1>
    <h2> See <a href="https://developer.mozilla.org/en-US/docs/Web/API/Storage">MDN Storage - Web Storage API</a>.</h2>
    <p>
      Click a button above. The style you select will be 'remembered' when you refresh this page. To reset this demo, click the 'Clear Storage' button.</p>
    <p>
        Faucibus interdum posuere lorem ipsum dolor sit amet, consectetur adipiscing elit duis tristique sollicitudin nibh sit amet commodo nulla facilisi? In metus vulputate eu scelerisque felis imperdiet proin fermentum leo.</p>
    <p>
        Etiam sit amet nisl purus, in mollis nunc sed id semper risus in! Ultricies lacus sed turpis tincidunt id aliquet risus feugiat in ante metus, dictum at tempor commodo, ullamcorper?</p>
    <button id="clear-storage">Clear Storage</button>
    <script src="script.js"></script>
</body>

</html>

light.css

body {
  background-color: #fff0bc;
}

h1, h2, p {
  color: #363636;
}

dark.css

body {
  background-color: #363636;
}

h1, h2, p {
  color: #fff0bc;
}

script.js

var buttons = document.getElementsByClassName("button");
var activeSheet = document.getElementById("active-stylesheet");
var clearStorageButton = document.getElementById("clear-storage");

// Test to see if localStorage already has a value stored
if (localStorage.getItem("lastActiveSheet")) {
     activeSheet.setAttribute("href", localStorage.getItem("lastActiveSheet"));
}

// Assign the event lister to each button
for (var i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener("click", switchStyle);  
}

// Create a button to clear localStorage
clearStorageButton.addEventListener("click", clearStorage);

// Set the #active-stylesheet to be the light or dark stylesheet
function switchStyle() {
   var selectedSheet = this.getAttribute("data-stylesheet");
   activeSheet.setAttribute("href", selectedSheet);
   localStorage.setItem("lastActiveSheet", selectedSheet);
}

// Wrapper function to localStorage.clear
function clearStorage() {
  localStorage.clear();
}

Source: https://stackoverflow.com/questions/52920019/save-current-stylesheet-to-local-storage


Answer by Bella Newman

Switching between stylesheets works perfectly.,So, here is the thing - I have two stylesheets on my site. I want to save lately used stylesheet to local storage.,I think you are confusing the idea of state here. In your code sample, you read value a from localStorage, but you did not attempt to set localStorage at any point.,If you want your app to remember the most recently used stylesheet, you need to store it into localStorage as a value you can use when the user visits your app again in the future.

Here is my code:

    window.onload = function() {
        var currentStylesheet = localStorage.getItem("stylesheet");
        document.getElementById("stylesheet").value = currentStylesheet;
        document.getElementById("stylesheet").setAttribute("href", currentStylesheet);
        }

Source: https://coderedirect.com/questions/460694/save-current-stylesheet-to-local-storage


Answer by Treasure Blair

Posting/Update Guidelines

var color = ["#ad9ea1", "#8e96a3", "#94a899", "#cfc5b6", "#91919c", "#b3b4b5"];
var i = 0;
document.querySelector("button").addEventListener("click", function() {
  i = 0 <= color.length ? ++i : 0;
  document.querySelector(".caro").style.background = color[i];
  if (i == 5) {
    i = 0;
  }
})

Source: https://www.codeproject.com/Questions/5288218/How-do-you-save-a-change-to-CSS-using-local-storag


Answer by Guillermo Goodwin

A Storage object which can be used to access the current origin's local storage space.,The following snippet accesses the current domain's local Storage object and adds a data item to it using Storage.setItem().,The localStorage read-only property of the window interface allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions.,The keys and the values stored with localStorage are always in the UTF-16 DOMString format, which uses two bytes per character. As with objects, integer keys are automatically converted to strings.

myStorage = window.localStorage;

Source: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage


Answer by Maxwell Ware

To follow this tutorial, basic HTML, CSS and JavaScript knowledge is required.,To set up our application, create a directory and, in it, create three files:,All Telerik .NET tools and Kendo UI JavaScript components in one package. Now enhanced with:,Subscribe to be the first to get our expert-written articles and tutorials for developers!

Fire up your favorite editor and add the following markup to your index.html file:

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="form.css" />
    <title>Save Later</title>
  </head>
  <body>
    <div class="alert"></div>
    <form id="save-later-form">
      <h3>Simple Save Later Form</h3>
      <label for="full-name">Full Name</label>
      <input type="text" name="full-name" id="full-name" />
      <label for="email">Email</label>
      <input type="email" name="email" id="email" />
      <label for="phone">Phone Number</label>
      <input type="tel" name="phone" id="phone" maxlength="11" />
      <label for="dob">Date Of Birth</label>
      <input type="date" name="dob" id="dob" />
      <label for="security">Security Question</label>
      <select name="security" id="security" tabindex="0">
        <option value="">Select a question</option>
        <option value="best-friend">What's your best friend's name?</option>
        <option value="pet">What's the name of your first pet?</option>
        <option value="spouse">Where did you meet your spouse?</option>
      </select>
      <label for="security-answer">Answer</label>
      <input type="text" name="security-answer" id="security-answer" />
      <label for="description">Description</label>
      <textarea
        name="description"
        id="description"
        placeholder="Describe yourself in 100 words"
      ></textarea>
      <button type="submit" id="submit">SUBMIT</button>
      <button type="submit" id="save">SAVE</button>
    </form>
  </body>
  <script src="form.js"></script>
</html>

In your form.css, add the following styles to make our form look presentable:

/* form.css */
@import url("https://fonts.googleapis.com/css?family=Nunito");

*,
*:before,
*:after {
  box-sizing: border-box;
}

body {
  background-color: whitesmoke;
  font-family: "Nunito", sans-serif;
}

h3,
label {
  text-transform: uppercase;
}

.alert {
  width: 80vw;
  margin: 2rem auto;
  background-color: #d4edda;
  color: #155724;
  padding: 0.75rem 1.25rem;
  border-radius: 0.25rem;
  display: none;
}

#save-later-form {
  position: relative;
  width: 80vw;
  margin: 3rem auto;
  background-color: white;
  padding: 1rem 2rem;
  border-radius: 3px;
}

label {
  margin: 1rem 0 0;
  display: block;
}

input {
  font-size: 0.875em;
  width: 100%;
  height: 40px;
  padding: 0px 15px 0px 15px;
  background: whitesmoke;
  outline: none;
  color: #000;
  border: none;
  border-radius: 3px;
}

input:hover {
  background: whitesmoke;
  color: black;
}

button[type="submit"] {
  background-color: #349bab;
  width: calc((100% / 2) - 3px);
  display: inline-block;
  color: white;
  font-weight: 600;
  height: 2.8rem;
  border: none;
  font-family: Nunito;
  font-size: 1rem;
  cursor: pointer;
  outline: none;
}

#save {
  background-color: #30383f;
}

select {
  width: 100%;
  height: 40px;
  background: whitesmoke;
  border: none;
  padding: 0 0 0 0.5rem;
  outline: none;
}

select:focus,
input:focus,
textarea:focus {
  outline: #349bab solid 1px;
}

textarea {
  width: 100%;
  max-width: 100%;
  height: 110px;
  max-height: 110px;
  padding: 15px;
  margin: 0 0 1rem 0;
  background: whitesmoke;
  outline: none;
  color: black;
  font-size: 0.875em;
  border: none;
}
/* ========MEDIA QUERIES======== */
@media screen and (min-width: 768px) {
  #save-later-form,
  .alert {
    width: 60vw;
  }
}

@media screen and (min-width: 992px) {
  #save-later-form,
  .alert {
    width: 40vw;
  }
}

Add the following code in your form.js file:

// form.js

const formId = "save-later-form"; // ID of the form
const url = location.href; //  href for the page
const formIdentifier = `${url} ${formId}`; // Identifier used to identify the form
const saveButton = document.querySelector("#save"); // select save button
const alertBox = document.querySelector(".alert"); // select alert display div
let form = document.querySelector(`#${formId}`); // select form
let formElements = form.elements; // get the elements in the form

Add the following to the end of your form.js file:

// form.js
...

/**
 * This function gets the values in the form
 * and returns them as an object with the
 * [formIdentifier] as the object key
 * @returns {Object}
 */
const getFormData = () => {
  let data = { [formIdentifier]: {} }; // create an empty object with the formIdentifier as the key and an empty object as its value
  for (const element of formElements) {
    if (element.name.length > 0) {
      data[formIdentifier][element.name] = element.value;
    }
  }
  return data;
};

saveButton.onclick = event => {
  event.preventDefault();
  data = getFormData();
  localStorage.setItem(formIdentifier, JSON.stringify(data[formIdentifier]));
  const message = "Form draft has been saved!";
  displayAlert(message);
};

/**
 * This function displays a message
 * on the page for 1 second
 *
 * @param {String} message
 */
const displayAlert = message => {
  alertBox.innerText = message; // add the message into the alert box
  alertBox.style.display = "block"; // make the alert box visible
  setTimeout(function() {
    alertBox.style.display = "none"; // hide the alert box after 1 second
  }, 1000);
};

Let’s add the code to achieve this to the end of our form.js file:

// form.js

...
/**
 * This function populates the form
 * with data from localStorage
 *
 */
const populateForm = () => {
  if (localStorage.key(formIdentifier)) {
    const savedData = JSON.parse(localStorage.getItem(formIdentifier)); // get and parse the saved data from localStorage
    for (const element of formElements) {
      if (element.name in savedData) {
        element.value = savedData[element.name];
      }
    }
    const message = "Form has been refilled with saved data!";
    displayAlert(message);
  }
};
document.onload = populateForm(); // populate the form when the document is loaded

If you’ve followed so far, your form.js file should look like this:

// form.js
const formId = "save-later-form"; // ID of the form
const url = location.href; //  href for the page
const formIdentifier = `${url} ${formId}`; // Identifier used to identify the form
const saveButton = document.querySelector("#save"); // select save button
const alertBox = document.querySelector(".alert"); // select alert display div
let form = document.querySelector(`#${formId}`); // select form
let formElements = form.elements; // get the elements in the form

/**
 * This function gets the values in the form
 * and returns them as an object with the
 * [formIdentifier] as the object key
 * @returns {Object}
 */
const getFormData = () => {
  let data = { [formIdentifier]: {} };
  for (const element of formElements) {
    if (element.name.length > 0) {
      data[formIdentifier][element.name] = element.value;
    }
  }
  return data;
};

saveButton.onclick = event => {
  event.preventDefault();
  data = getFormData();
  localStorage.setItem(formIdentifier, JSON.stringify(data[formIdentifier]));
  const message = "Form draft has been saved!";
  displayAlert(message);
};

/**
 * This function displays a message
 * on the page for 1 second
 *
 * @param {String} message
 */
const displayAlert = message => {
  alertBox.innerText = message;
  alertBox.style.display = "block";
  setTimeout(function() {
    alertBox.style.display = "none";
  }, 1000);
};

/**
 * This function populates the form
 * with data from localStorage
 *
 */
const populateForm = () => {
  if (localStorage.key(formIdentifier)) {
    const savedData = JSON.parse(localStorage.getItem(formIdentifier)); // get and parse the saved data from localStorage
    for (const element of formElements) {
      if (element.name in savedData) {
        element.value = savedData[element.name];
      }
    }
    const message = "Form has been refilled with saved data!";
    displayAlert(message);
  }
};

document.onload = populateForm(); // populate the form when the document is loaded

Source: https://www.telerik.com/blogs/save-for-later-feature-in-forms-using-localstorage


Answer by Misael Sexton

In this article, I’ll guide you through how to create your very own using CSS Variables, some basic JavaScript, and the use of localStorage!,Creating our CSS Variables,And there we go! A fully functioning light/dark mode using CSS Variables, some basic JavaScript and localStorage.,We will be using CSS Custom Properties, better known as CSS Variables, which we can reference and modify in our CSS file.

:root {  --bg-color: #fec150;  --font-color: #222;  --title-color: #0067e6;  --title-background: #fff;  --main-border: 1px solid rgba(255, 255, 255, 0.4);  --main-bg: rgba(255, 255, 255, 0.4);}
[data-theme="dark"] {  --bg-color: #111;  --font-color: #efefef;  --title-color: #fec150;  --title-background: #222;  --main-border: 1px solid rgba(255, 255, 255, 0.2);  --main-bg: rgba(25, 25, 25, 0.4);}
body {  color: var(--font-color);  background-color: var(--bg-color);/* OTHER STYLING */  ...}main {  border: var(--main-border);  background: var(--main-bg);/* OTHER STYLING */  ...}h1 {  color: var(--title-color);/* OTHER STYLING */  ...}

Source: https://blog.prototypr.io/create-your-own-dark-mode-using-js-css-variables-and-localstorage-8b461864644b


Answer by Celine Baker

a JavaScript localStorage example with a rich text editor,a simple JavaScript localStorage example,an overview of JavaScript localStorage methods,There are four basic JavaScript methods you can use to access and work with localStorage:

> localStorage
< Storage {length: 0}

Source: https://www.tiny.cloud/blog/javascript-localstorage/


Answer by Giuliana McIntyre

Let's save the name to the local storage in the formSubmitHandler function:,Now, let's import the stylesheet files related to BluePrintJS in index.css and we will add some basic styling:,Here we are storing the name in the local storage and we are not doing anything when the form is submitted.,If you run the application and submit the form, you will be able to see the name getting saved in the localStorage:

1npx create-react-app react-local-storage

Source: https://www.codingdeft.com/posts/react-local-storage/


Answer by Orion Leon

form-storage is a small JavaScript library to store the current values of your form fields in the local storage to prevent data loss.,Save the current form status in the local storage.,Or directly include the JavaScript file ‘form-storage.js’ on the webpage.,The saved values will be automatically restored any time when needed such as refresh, next visit, etc.

Install the form-storage via package managers:

# Yarn
$ yarn add form-storage

# NPM
$ npm install form-storage --save

Import the library as a module.

// ES 6
import FormStorage from 'form-storage';

Or directly include the JavaScript file ‘form-storage.js’ on the webpage.

<script src="form-storage.js"></script>

Apply the form-storage to your HTML form.

var formStorage = new FormStorage('.js-form');
formStorage.apply();

Save the current form status in the local storage.

formStorage.save();

You can specify an array of form fields to include or exclude.

var formStorage = new FormStorage('.js-form',{
    ignores: [],
    includes: [],
});

Create a checkbox to save data before submitting.

<label>
  <input type="checkbox" class="js-persist" />
  Allow saving form-data to localstorage.
</label>
<label>
  <input type="checkbox" class="js-persist" />
  Allow saving form-data to localstorage.
</label>
var formStorage = new FormStorage('.js-form',{
    checkbox: '.js-persist'
});

Customize the localstorage name.

var formStorage = new FormStorage('.js-form',{
    name: 'form-storage'
});

Clear the stored data.

formStorage.clear();

Source: https://www.cssscript.com/save-form-changes-local-storage/