Data storage is a crucial component of web development. Many online applications require you to remember user settings, form data, or application states. JavaScript offers several options for storing data directly within an HTML file. This article will look at five practical ways to accomplish this: localStorage, sessionStorage, cookies, elements, and JavaScript objects with data properties. Let's go over each strategy in depth!
Join Index.dev for high-paying remote JavaScript projects!
Using localStorage
Definition & Overview
LocalStorage is part of the Web Storage API. It lets you save data as key-value pairs in a web browser. The data stored in localStorage is retained even when the browser is closed. This means that when consumers return to your website, their settings or preferences will remain unchanged.
Implementation Example
Here's a basic example of using localStorage to save and get a user's name:
// Saving data
localStorage.setItem('username', 'JohnDoe');
// Retrieving data
const username = localStorage.getItem('username');
console.log(username); // Output: JohnDoe
// Removing data
localStorage.removeItem('username');Use Cases
LocalStorage is helpful for saving user preferences, such as theme settings, language preferences, and other customization choices. For example, if a user chooses a dark mode for your website, you may preserve their selection in localStorage so that it is remembered the next time they come.
Using sessionStorage
Definition & Overview
SessionStorage is identical to localStorage, but with one important distinction: it keeps data for the life of the page session. This indicates that data kept in sessionStorage is deleted when the page session expires, which happens when the tab or window is closed.
Implementation Example
Here's how you can use sessionStorage to manage user input in a one-page application:
// Saving data
sessionStorage.setItem('cartItems', JSON.stringify(['item1', 'item2', 'item3']));
// Retrieving data
const cartItems = JSON.parse(sessionStorage.getItem('cartItems'));
console.log(cartItems); // Output: ['item1', 'item2', 'item3']
// Clearing all session storage
sessionStorage.clear();Use Cases
SessionStorage is useful for storing transitory data, such as user input in forms. If a user is completing a multi-step form, you may preserve their progress with sessionStorage. If users unintentionally shut the tab, they will not lose their input as long as they reopen it during the session.
Using Cookies
Definition & Overview
Cookies are little bits of data transmitted by a server and kept in the user's browser. They can store data like user preferences or session IDs. Cookies can have expiration dates, which implies they can be configured to expire after a certain time.
Implementation Example
Here's how to create, read, and remove cookies with JavaScript:
// Function to set a cookie
function setCookie(name, value, days) {
let expires = '';
if (days) {
const date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toUTCString();
}
document.cookie = name + '=' + (value || '') + expires + '; path=/';
}
// Function to get a cookie
function getCookie(name) {
const nameEQ = name + '=';
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
// Function to delete a cookie
function eraseCookie(name) {
document.cookie = name + '=; Max-Age=-99999999;';
}
// Usage
setCookie('user', 'JaneDoe', 7); // Set cookie
console.log(getCookie('user')); // Output: JaneDoe
eraseCookie('user'); // Delete cookieUse Cases
Cookies are commonly used for user authentication, and a session cookie can remember that a user is logged in. They can also be used for tracking or storing user preferences over numerous visits to a website.
Using Elements
Definition & Overview
HTML elements can save data directly in the HTML file. You may use hidden input fields to store data that is not visible to users but is required for processing.
Implementation Example
Here's how to utilize hidden inputs to store data:
<form id="myForm">
<input type="hidden" id="userEmail" value="[email protected]">
<button type="button" onclick="submitForm()">Submit</button>
</form><script>
function submitForm() {
const email = document.getElementById('userEmail').value;
console.log(email); // Output: [email protected]
}
</script>Use Cases
Hidden inputs are excellent for storing data that must be supplied through a form but should not be shown to users. This might include IDs or other data that has to be processed on the server.
Using JavaScript Objects and Data Attributes
Definition & Overview
JavaScript objects may also be used to temporarily store data during a session. HTML5 also provided custom data attributes (data-*), which can be applied to HTML elements to hold additional information.
Implementation Example
Here is an example of how to use data attributes in an HTML element:
<div id="userProfile" data-user-id="123" data-user-name="Alice">Profile</div><script>
const userProfile = document.getElementById('userProfile');
const userId = userProfile.getAttribute('data-user-id');
const userName = userProfile.getAttribute('data-user-name');
console.log(userId); // Output: 123
console.log(userName); // Output: Alice
</script>Use Cases
Using JavaScript objects, you may manage application state momentarily, whereas data attributes are ideal for keeping information about individual HTML components. This approach is useful for interactive parts in which you may need to access or alter user data.
Read more: 10 Ways to Iterate Through an Object in JavaScript
Conclusion
This blog covers five ways to store data in an HTML file using JavaScript: localStorage, sessionStorage, cookies, elements, and JavaScript objects with data properties. Each approach has its pros and applications. You can select the approach that is most suited to your web application's requirements.
Experiment with these strategies in your projects to determine the best way to handle data for your users!
For Developers:
Join Index.dev’s global network to find high-paying remote JavaScript projects and work with top companies worldwide.
For Clients:
Hire skilled JavaScript developers from Index.dev’s vetted talent pool. Start risk-free and find the right expert within 48 hours!