Mastering Local Storage in Web Development: 8 Practical Examples, From Novice to Expert! #3

Local storage is a useful web development tool that enables developers to save data within the user’s browser. In this article, we’ll look at different features of local storage, starting with beginner-level examples and continuing to more complex techniques. By the end of this guide, you will have a basic understanding of how to successfully use local storage in web applications.

Beginner level Examples on Local storage

1. Storing User Preferences :

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Preferences</title>
</head>

<body>
    <label for="theme">Choose a theme:</label>
    <select id="theme">
        <option value="light">Light</option>
        <option value="dark">Dark</option>
        <option value="medium">Medium</option>
    </select>
    <button onclick="savePreference()">Save Preference</button>

    <script>
        function savePreference() {
            const selectedTheme = document.getElementById('theme').value;
            localStorage.setItem('theme', selectedTheme);
            console.log('Preference saved:', selectedTheme);
            alert('Preference saved!' + " " + selectedTheme);
        }
    </script>
</body>

</html>

When the user selects a theme and hits the “Save Preference” button, this code logs the theme to the console. To read this log, open the browser’s developer tools (typically by pressing F12 or right-clicking on the page and selecting “Inspect”) and go to the console tab.

2. Remembering User Input :

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Remember User Input</title>
</head>

<body>
    <input type="text" id="userInput">
    <button onclick="saveInput()">Save Input</button>

    <script>
        function saveInput() {
            const userInput = document.getElementById('userInput').value;
            localStorage.setItem('savedInput', userInput);
            console.log(userInput + " " + 'saved !');
            alert('Input saved!');
        }
    </script>
</body>

</html>

This HTML example generates a simple web page that allows users to enter text into a text field and save it to their browser’s local storage.

When a user types text into the input box and hits the “Save Input” button, the text is saved in the browser’s local storage. This implies that even if users refresh the website or close and reopen the browser, the saved input will remain accessible. The console log and alert notify the user that their input has been successfully saved.

3. Shopping Cart Persistence :

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Shopping Cart</title>
</head>

<body>
    <h1>Shopping Cart</h1>
    <ul id="cartItems"></ul>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const savedCart = JSON.parse(localStorage.getItem('cart')) || [];
            const cartItemsElement = document.getElementById('cartItems');

            savedCart.forEach(item => {
                const li = document.createElement('li');
                li.textContent = item;
                cartItemsElement.appendChild(li);
            });
            console.log('Saved cart items:', savedCart);
        });

        function addToCart(item) {
            const savedCart = JSON.parse(localStorage.getItem('cart')) || [];
            savedCart.push(item);
            localStorage.setItem('cart', JSON.stringify(savedCart));
            console.log('Added', item, 'to cart');
            location.reload(); // Refresh the page to reflect changes
        }
    </script>

    <button onclick="addToCart('Item 1')">Add Item 1 to Cart</button>
    <button onclick="addToCart('Item 2')">Add Item 2 to Cart</button>
    <button onclick="addToCart('Item 3')">Add Item 3 to Cart</button>
</body>

</html>

This example shows how to save a shopping cart using local storage. Items added to the cart are saved as an array in local storage under the key ‘cart’. When the page loads, the saved cart items are pulled from local storage and shown.

When you click one of the “Add Item X to Cart” buttons, the appropriate item is added to the shopping cart, and the updated cart contents are displayed in the console. To inspect these logs, open the browser’s developer tools (typically by pressing F12 or right-clicking on the page and selecting “Inspect”) and go to the console tab.

You can also view the local storage directly through the browser’s developer tools. Most browsers allow you to do this by right-clicking on the page, selecting “Inspect” to get the developer tools, and then navigating to the “Application” or “Storage” tab. From there, expand the “Local Storage” section to view the website’s key-value pairs. In this example, the key “cart” includes the JSON string representing the saved cart items.

4. Remembering User Login State :

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Login</title>
</head>

<body>
    <div id="loginContainer">
        <input type="text" id="username" placeholder="Username">
        <input type="password" id="password" placeholder="Password">
        <button onclick="login()">Login</button>
    </div>

    <div id="loggedInUser" style="display: none;">
        <p>Welcome, <span id="user"></span>!</p>
        <button onclick="logout()">Logout</button>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const user = localStorage.getItem('user');
            if (user) {
                document.getElementById('loggedInUser').style.display = 'block';
                document.getElementById('user').textContent = user;
            } else {
                document.getElementById('loginContainer').style.display = 'block';
            }
        });

        function login() {
            const username = document.getElementById('username').value;
            localStorage.setItem('user', username);
            location.reload(); // Refresh the page to reflect changes
        }

        function logout() {
            localStorage.removeItem('user');
            location.reload(); // Refresh the page to reflect changes
        }
    </script>
</body>

</html>

Login Form: The HTML includes a login form with username and password input fields and a login button. This form is contained in a div element with ID “loginContainer”.

Display  logic: The login form is initially displayed and hidden in a separate div with ID “loggedInUser”. This is achieved through CSS styling.

User Authentication: When the page loads, JavaScript checks if the user is saved in the browser’s local storage. If the user is found, it hides the login form and displays a welcome message and a logout button. If the user is not found, a login form is displayed.

Login function: When a user enters their username and clicks the login button, JavaScript saves the username in the browser’s local storage. It then reloads the page according to the changes. It effectively simulates a user login.

Logout function: When the user clicks the logout button, JavaScript deletes the user’s data from local memory and reloads the page to show that the user is logged out.

Dynamic content: The welcome message dynamically displays the username of the logged in user. This is achieved by updating the text content of the span element with the id “user” when the user is logged in.

Intermediate level Examples on Local storage

1. Form Data Persistence :

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form Data Persistence</title>
</head>

<body>
    <form id="userForm">
        <label for="name">Name:</label>
        <input type="text" id="name">
        <label for="email">Email:</label>
        <input type="email" id="email">
        <button type="submit">Submit</button>
    </form>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const nameInput = document.getElementById('name');
            const emailInput = document.getElementById('email');

            // Populate form fields with saved data
            nameInput.value = localStorage.getItem('name') || '';
            emailInput.value = localStorage.getItem('email') || '';

            // Save form data on form submission
            document.getElementById('userForm').addEventListener('submit', (event) => {
                event.preventDefault();
                localStorage.setItem('name', nameInput.value);
                localStorage.setItem('email', emailInput.value);
                alert('Form data saved successfully!');
            });
        });
    </script>
</body>

</html>

This is an example of a simple HTML text containing a form for collecting the user’s name and email. It contains JavaScript code that adds capabilities to save entered data even after the page is reloaded or closed.

When the page loads, the JavaScript code awaits the DOMContentLoaded event before proceeding. This ensures that all components in the HTML document are completely loaded before any alteration takes place.

Inside the JavaScript code:

It retrieves references to the name and email input fields from the HTML document using their respective IDs.

It then checks if there’s any previously saved data for the name and email in the localStorage.

If there is saved data, it populates the input fields with that data; otherwise, it leaves them empty.

It adds an event listener to the form submission event.

When the form is submitted, it prevents the default form submission behavior (which would cause the page to reload).

It then stores the entered name and email into the localStorage.

Finally, it displays an alert indicating that the form data has been saved successfully.

This manner, when the user enters their name and email address and submits the form, the data is saved locally, and even if they refresh the page or close and reopen it, the submitted data remains.

2. Remembering User Preferences with JSON :

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Preferences</title>
</head>

<body>
    <label for="theme">Choose a theme:</label>
    <select id="theme">
        <option value="light">Light</option>
        <option value="dark">Dark</option>
        <option value="red">Red</option>
        <option value="blue">Blue</option>
        <option value="pink">Pink</option>
    </select>
    <button onclick="savePreference()">Save Preference</button>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const savedPreferences = JSON.parse(localStorage.getItem('preferences')) || {};
            document.getElementById('theme').value = savedPreferences.theme || 'light';
        });

        function savePreference() {
            const selectedTheme = document.getElementById('theme').value;
            const preferences = { theme: selectedTheme };
            localStorage.setItem('preferences', JSON.stringify(preferences));
            alert('Preference saved!');
        }
    </script>
</body>

</html>

This HTML document creates a simple user preferences system. It has a dropdown menu where users can choose a theme (light, dark, red, blue, or pink) and a button to save their selection.

When the website loads, it looks for previously saved preferences in the browser’s local storage. If preferences are detected, it changes the dropdown menu to the previously specified theme; otherwise, it defaults to the light theme.

When a user selects a theme and hits the “Save Preference” button, the savePreference() method is called. This function retrieves the currently selected theme from the dropdown menu, builds an object containing this preference, converts it to a JSON string, and saves it to the browser’s local storage under the key “preferences”. Finally, it shows an alert verifying that the preference was saved.

This configuration allows the user’s theme option to persist across sessions because it is saved locally in the browser.

3. Offline Data Synchronization :

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Offline Data Sync</title>
</head>

<body>
    <h1>Offline Data Synchronization</h1>
    <textarea id="data"></textarea>
    <button onclick="saveData()">Save Data</button>
    <button onclick="syncData()">Sync Data</button>

    <script>
        function saveData() {
            const data = document.getElementById('data').value;
            localStorage.setItem('unsyncedData', data);
            alert('Data saved locally!');
        }

        function syncData() {
            const unsyncedData = localStorage.getItem('unsyncedData');
            // Code to synchronize data with server goes here
// We will provide this code in the next blog post on data synchronization
            // Once synchronization is successful, clear local storage
            localStorage.removeItem('unsyncedData');
            alert('Data synchronized with server!');
        }
    </script>
</body>

</html>

This HTML document shows a simple offline data syncing technique. It has a textarea where users may enter data and two buttons: one for saving the data locally and the other for synchronizing the data with a server.

When a user enters data and then clicks the “Save Data” button, the saveData() method is called. This function receives the data from the textarea, saves it to the browser’s local storage under the key “unsyncedData”, and shows an alert confirming that the data was saved locally.

When the user clicks on the “Sync Data” button, the syncData() method is called. This function obtains unsynchronized data from local storage, which is then often sent to a server for synchronization. After successful synchronization, it deletes the “unsyncedData” key from local storage and shows an alert confirming that the data has been synchronized with the server.

The actual code responsible for synchronizing the data with the server is not provided in this example and would need to be implemented separately. However, we intend to include it in our next blog post on data synchronization.

4. Session Management :

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Session Management</title>
</head>

<body>
    <h1>Session Management</h1>
    <button onclick="login()">Login</button>
    <button onclick="logout()">Logout</button>

    <script>
        function login() {
            localStorage.setItem('isLoggedIn', 'true');
            alert('Logged in successfully!');
        }

        function logout() {
            localStorage.removeItem('isLoggedIn');
            alert('Logged out successfully!');
        }

        // Check if user is logged in on page load
        document.addEventListener('DOMContentLoaded', () => {
            const isLoggedIn = localStorage.getItem('isLoggedIn');
            if (isLoggedIn) {
                alert('Welcome back!');
            }
        });
    </script>
</body>

</html>

This HTML document shows how a simple session management system can be implemented utilizing browser local storage.

When the page loads, it determines whether the user is logged in by getting a key from local storage. If the key exists, a welcome message is displayed, indicating that the user has logged in.

There are two buttons available: “Login” and “Logout”. When the “Login” button is selected, a key is stored in local storage to indicate that the user has logged in, and an alert is displayed to validate the successful login. Similarly, when the “Logout” button is hit, the key is removed from local storage, indicating that the user has logged out, and an alert is displayed confirming the successful logout.

Furthermore, if the user was logged in during their previous visit and refreshes or revisits the page later, they are presented with a “Welcome back!” alert message. This feature improves the user experience by recognizing recurring users and enabling smooth session management within the browser using local storage.

Basic of Web Storage : Web Storage API Essentials: Everything You Need to Know to Get Started – #1

Advanced Local Storage Techniques : Advanced Local Storage Techniques: Applying the Power of JSON with Examples #2

CSSHTMLJavascriptWeb Storage

Recent Blogs

Understanding the SWITCH Function in Excel: A Comprehensive Guide with 3 Examples

Excel, Microsoft’s widely used spreadsheet software, is a vital tool in a variety of professions, including marketing. Among its numerous functions, the SWITCH function is notable for its ability to simplify complicated logical situations. This blog post will provide a thorough knowledge of the SWITCH function, enhanced with actual business examples to demonstrate its usefulness. […]

Mastering the Art of CSS Translate Property: A Comprehensive Guide with 6 examples

What is Translate Property in CSS? CSS translate property moves an element along the X and Y axes. Unlike other positioning attributes, such as position, translate does not disrupt the document’s natural flow, making it excellent for producing smooth animations and transitions. What is Transform property in CSS Visually appealing and dynamic user interfaces have […]

CSSHTMLJavascriptWeb design

Ready to Maximize Your Design Potential? : Illustrator’s Variable Helps You to Automate 100s of Unique Designs

Illustrator’s Variable – Variables in Adobe Illustrator offer a powerful way to streamline design workflows, especially for projects with repetitive elements or variable data. Whether you’re creating personalized invitations, data-driven infographics, or dynamic packaging designs, mastering variables can significantly enhance your efficiency and productivity. In this step-by-step guide, we’ll explore how to harness the full potential of variables in Illustrator.

Graphic DesignIllustrator

CSS Rotate Property Explained: 5 Hands-On Examples for Web Developers

Understanding the CSS Rotate Property: The rotate property is part of the CSS transform module, which allows developers to apply different transformations to elements on a webpage. The rotate function allows you to rotate items by a specified angle, changing their orientation but not their location in the document flow. This characteristic provides tremendous versatility […]

CSSHTMLJavascriptWeb design