Mastering Local Storage in Web Development

王林
Release: 2024-07-24 15:26:50
Original
547 people have browsed it

Mastering Local Storage in Web Development

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 :

<!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>

Copy after login

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.(Read More)

2. Remembering User Input :

<!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>

Copy after login

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. (Read More)

3. Shopping Cart Persistence :

<!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>

Copy after login

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.
Read full article - Mastering Local Storage in Web Development: 8 Practical Examples, From Novice to Expert!

Learn Json- Click Here

The above is the detailed content of Mastering Local Storage in Web Development. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template