Local Storage API in HTML5

 Local Storage API in HTML5


 HTML5 includes a new API for storing data on the client-side, called the Local Storage API. This API allows web developers to store data locally on the user's device, which can be useful for caching data or saving user preferences. Here's an example of how to use the Local Storage API to save and retrieve a user's name:

php


<!DOCTYPE html>

<html>

<head>

<title>My Web Page</title>

<script>

function saveName() {

var name = document.getElementById("name").value;

localStorage.setItem("name", name);

alert("Name saved!");

}


function loadName() {

var name = localStorage.getItem("name");

if (name) {

document.getElementById("greeting").innerHTML = "Hello, " + name + "!";

}

}

</script>

</head>

<body onload="loadName()">

<label for="name">Enter your name:</label>

<input type="text" id="name">

<button onclick="saveName()">Save</button>

<p id="greeting"></p>

</body>

</html>

In this example, we use the Local Storage API to store and retrieve a user's name. When the user enters their name and clicks the "Save" button, we use the setItem() method to save the name in local storage. When the page is reloaded, we use the getItem() method to retrieve the name from local storage, and display a personalized greeting using the name.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...