Recipe 2.2
Persisting String Data
A simple string value is a perfect use case for local storage. It can be stored and loaded without performing any serialization or conversion. This makes it well suited to “remembering” default form values.
This example has a color picker that uses local storage to remember the last color selected, and sets it as the default color when the page is reloaded.
Demo
Code
JavaScript
// A reference to the color picker input element.
const colorPicker = document.querySelector('#colorPicker');
// Load the saved color, if any, and set it on the color picker.
const storedValue = localStorage.getItem('savedColor');
if (storedValue) {
console.log('Found saved color:', storedValue);
colorPicker.value = storedValue;
}
// Update the saved color whenever the value changes.
colorPicker.addEventListener('change', event => {
localStorage.setItem('savedColor', colorPicker.value);
console.log('Saving new color:', colorPicker.value);
});
HTML
<div>
<label for="colorPicker" class="form-label">Select a color</label>
<input type="color" class="form-control" id="colorPicker">
</div>