storage-form is a Web Component to allow regular form elements to interact with the browsers local storage. This can be really useful when building websites or small applications that need to be able to store data for later use, such as personal website viewing preferences (also known as light/dark mode).
storage-form
<storage-form> connects regular <form> elements up to localStorage within the browser. This allows the use of standard form elements such as input to add, update and remove data within the users browser local storage.
Usage
The <storage-form> component can be used with the help of a script tag and placing a typical form within it like so:
<script type="module" src="storage-form.js"></script>
<storage-form>
<form>
<label>
Example
<input type="text" name="example" value="value" />
</label>
<button>Submit</button>
</form>
</storage-form>storage-form example usage
Features
This Web Component allows you to:
- Use regular form elements to manipulate data in local storage
- Invoke a
storageevent on the page to hook into elsewhere on the page - Maintain the forms state, using local storage, when the page is refreshed or reloaded
- Optionally submit the form on the forms
changeevent by omitting the forms submit button/input element
Light/dark and high contrast mode example
A good example of using this component and the features mentioned above is to create user preferences for your website so people can control the colour scheme and contrast levels. The following example utilises the automatic form submission feature when the submit button is omitted:
<script type="module" src="storage-form.js"></script>
<storage-form>
<form>
<label>
<input type="radio" name="theme" value="dark" />
<span>Dark mode</span>
</label>
<label>
<input type="radio" name="theme" value="light" />
<span>Light mode</span>
</label>
<label>
<input type="radio" name="theme" value="" checked />
<span>Default mode</span>
</label>
<br />
<label>
<input type="hidden" name="contrast" value />
<input type="checkbox" name="contrast" value="true" />
<span>High contrast</span>
</label>
</form>
</storage-form>This example also maintains state between page refreshes, a feature which was added in version v2.0.0. Check out this live demo to see the above code in action.
Further reading
Check out the source code, documentation and more demos over on GitHub:
Hope you find this useful!