Curriculum
Course: HTML Basic
Login

Curriculum

HTML Basic

HTML Introduction

0/1

HTML Editors

0/1

HTML Attributes

0/1

HTML Paragraphs

0/1

HTML Formatting

0/1

HTML Comments

0/1

HTML Favicon

0/1

HTML Page Title

0/1

HTML Iframes

0/1

HTML Java Script

0/1

HTML File Paths

0/1

HTML Symbols

0/1
Text lesson

The localStorage Object

The localStorage object stores data indefinitely without an expiration date. Data persists even after the browser is closed and remains accessible in the future, whether it’s the next day, week, or year.

Example

// Store
localStorage.setItem(“lastname”“Smith”);

// Retrieve
document.getElementById(“result”).innerHTML = localStorage.getItem(“lastname”);

Here’s the example explained:

  1. Set a localStorage name/value pair with name=”lastname” and value=”Smith”.
  2. Retrieve the value of “lastname” and place it into the element with id=”result”.

The example above can alternatively be written as:

// Store
localStorage.lastname = “Smith”;
// Retrieve
document.getElementById(“result”).innerHTML = localStorage.lastname;

Here’s the syntax for removing the “lastname” localStorage item:

localStorage.removeItem(“lastname”);

Note: Name/value pairs in localStorage are always stored as strings. Remember to convert them to another format when necessary!

The following example demonstrates counting the number of times a user has clicked a button. In this code, the string value is converted to a number to increment the counter:

Example

if (localStorage.clickcount) {
  localStorage.clickcount = Number(localStorage.clickcount) + 1;
else {
  localStorage.clickcount = 1;
}
document.getElementById(“result”).innerHTML = “You have clicked the button “ +
localStorage.clickcount + ” time(s).”;

The sessionStorage Object

The sessionStorage object functions similarly to the localStorage object, but it stores data only for the duration of one session. Data stored in sessionStorage is deleted when the user closes the specific browser tab.

Here’s an example that counts the number of times a user has clicked a button in the current session:

Example

if (sessionStorage.clickcount) {
  sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
else {
  sessionStorage.clickcount = 1;
}
document.getElementById(“result”).innerHTML = “You have clicked the button “ +
sessionStorage.clickcount + ” time(s) in this session.”;