Saving data in localstorage. JavaScript example open

Saving data in localstorage. JavaScript example

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators

Storing data in local storage (localStorage) in JavaScript allows you to save data on the client side in the browser:

Lets create example page:

<!DOCTYPE html>
<html lang="ru">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Test Page</title>
</head>

<body>

    <input type="text">

    <button>Save</button>

    <script defer src="script.js" type="text/javascript"></script>
</body>

</html>

Let’s add a script:

    //add a button click action
    document.querySelector('button').addEventListener('click', function (event) {

        //we get the value from input
        var value = document.querySelector('input').value

        var obj = {
            text: value
        }


        localStorage.setItem('Name', JSON.stringify(obj))
        //The name of the parameter in localStorage
        //JSON.stringify(obj) - we pass the term that we want to save as a parameter

    })

    document.addEventListener('DOMContentLoaded', function () {


        let text = localStorage.getItem('Name')//let's get our object from localstorage
		
		//Removing data from localStorage
		localStorage.removeItem('Name');

    })
Please note that data stored in localStorage remains available even after you reload the page or close the browser. They persist until you explicitly delete them or clear localStorage.

Another example of use:

0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation