Exploring Session Storage in JavaScript


Session Storage is a web storage mechanism available in JavaScript that allows you to store key-value pairs of data on the client side, similar to cookies and local storage. However, unlike cookies, session storage is temporary and has a limited scope.

Temporary Storage : Data stored in session storage is only available for the duration of a page session. A session typically lasts as long as the user has the web page open and ends when the user closes the tab or browser. This makes session storage useful for temporarily storing data that you only need while the user is interacting with your website.

Data Persistence : Unlike local storage, session storage data is not persistent across browser sessions. It will be automatically cleared when the user closes the browser tab or window.

Scope : Unlike local storage, session storage data is not persistent across browser sessions. It will be automatically cleared when the user closes the browser tab or window.

Simple API : Session storage provides a simple API to store and retrieve data. You can use the sessionStorage object in JavaScript to set and get data using key-value pairs.

Data Types : Session storage can store various data types, including strings, numbers, objects, and arrays. The data is automatically serialized to strings when stored and deserialized when retrieved.

Storage Limitations : Like other web storage mechanisms, session storage has limitations on the amount of data you can store. It typically allows for more storage space (usually around 5-10 MB) compared to cookies but less than local storage.

No Expiry : Data stored in session storage does not have an expiration date. It will remain available until the end of the session or until explicitly removed.

No Cross-Origin Access : Similar to other client-side storage mechanisms, session storage follows the same-origin policy. This means that JavaScript code from one domain cannot access or manipulate session storage data from another domain.

sample Code

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Step-1</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <h1>Multi-Step Form Session Storage</h1>
      <h2>Step 1 - Personal Details</h2>
      <form>
        <label for="name">Name</label>
        <input type="text" id="name" placeholder="Enter Full Name" />
        <label for="email">Email:</label>
        <input type="email" id="email" placeholder="Enter Email Address" />
        <button type="button" id="btnStep1Next">Next Step</button>
      </form>
    </div>
    <script>
      const name = document.getElementById("name");
      const email = document.getElementById("email");
      const btnStep1Next = document.getElementById("btnStep1Next");

      function loadSession() {
        let data = sessionStorage.getItem("formData") || {};
        if (data.length > 0) {
          data = JSON.parse(data);
          name.value = data.name;
          email.value = data.email;
        }
      }
      loadSession();
      btnStep1Next.addEventListener("click", function () {
        if (name.value != "" && email.value != "") {
          const formData = JSON.parse(sessionStorage.getItem("formData")) || {};

          formData.name = name.value;
          formData.email = email.value;

          sessionStorage.setItem("formData", JSON.stringify(formData));
          window.location.href = "http://127.0.0.1:5500/step2.html";
        } else {
          alert("Please Fill All Details");
          name.focus();
        }
      });
    </script>
  </body>
</html>
  1. The JavaScript code is embedded within a <script> tag at the end of the <body>.
  2. It starts by selecting and storing references to the "Name" input field (name), the "Email" input field (email), and the "Next Step" button (btnStep1Next) in variables.
  3. loadSession() Function:
    • The loadSession() function is defined to load data from session storage and populate the form fields with any previously entered data. It is called immediately when the page loads.
    • It retrieves the "formData" item from session storage, which is expected to be a JSON string.
    • If there is data in session storage, it parses the JSON data and populates the "Name" and "Email" input fields with the saved values.
  4. Event Listener for "Next Step" Button:
    • An event listener is added to the "Next Step" button (btnStep1Next) that triggers an action when the button is clicked.
    • When the button is clicked, the code checks if both the "Name" and "Email" fields are filled out.
    • If both fields have values, it creates or retrieves a formData object from session storage, adds the "Name" and "Email" values to it, and then stores this updated object back in session storage as a JSON string.
    • Finally, it redirects the user to "step2.html" using window.location.href, assuming that this is the URL for the next step of the multi-step form.
  5. Data Validation

    Before storing data in session storage, the code checks if the "Name" and "Email" fields are filled out. If not, it displays an alert to prompt the user to fill in all the details and focuses on the "Name" field.

step2.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Step-2</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <h1>Multi-Step Form Session Storage</h1>
      <h2>Step 2 - Additional Details</h2>
      <form>
        <label for="address">Address:</label>
        <input type="text" id="address" placeholder="Full Address" />

        <label for="phone">Phone:</label>
        <input type="text" id="phone" placeholder="Enter Contact Number" />

        <button type="button" id="btnStep1Back">Back Step</button>
        <button type="button" id="btnStep2Next">Next Step</button>
      </form>
    </div>
    <script>
      const address = document.getElementById("address");
      const phone = document.getElementById("phone");
      const btnStep1Back = document.getElementById("btnStep1Back");
      const btnStep2Next = document.getElementById("btnStep2Next");

      function loadSession() {
        let data = sessionStorage.getItem("formData") || {};
        if (data.length > 0) {
          data = JSON.parse(data);
          address.value = data.address == undefined ? "" : data.address;
          phone.value = data.phone == undefined ? "" : data.phone;
        }
      }
      loadSession();

      btnStep1Back.addEventListener("click", function () {
        window.location.href = "http://127.0.0.1:5500/index.html";
      });

      btnStep2Next.addEventListener("click", function () {
        if (address.value != "" && phone.value != "") {
          const formData = JSON.parse(sessionStorage.getItem("formData")) || {};

          formData.address = address.value;
          formData.phone = phone.value;

          sessionStorage.setItem("formData", JSON.stringify(formData));
          window.location.href = "http://127.0.0.1:5500/review.html";
        } else {
          alert("Please Fill All Details");
          address.focus();
        }
      });
    </script>
  </body>
</html>
  1. loadSession() Function:
    • The loadSession() function is defined to load and display data from session storage.
    • It retrieves the "formData" item from session storage, which is expected to be a JSON string.
    • It then parses the JSON data into a JavaScript object.
    • Next, it constructs an HTML table (inside the output variable) with rows for "Name," "Email," "Address," and "Contact No" and populates the corresponding data from the data object.
    • Finally, it sets the innerHTML of the "dataTable" table element to the generated HTML, effectively displaying the user-entered data.
  2. loadSession() Execution
    • The loadSession() function is called immediately after it's defined, ensuring that the user's entered data is displayed when the page loads.

In summary, this code represents the "Review" step of a multi-step form. It retrieves user-entered data from session storage, displays it in a tabular format, and provides a "Back Step" button to allow the user to return to the previous step if needed. Additionally, there is a "Confirm Submission" button, which appears to be intended for the user to confirm their form submission, but its functionality is not implemented in the provided code.

review.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Review</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <h1>Multi-Step Form Session Storage</h1>
      <h2>Review Details</h2>
      <table id="dataTable"></table>

      <button type="button" id="btnStep2Back">Back Step</button>
      <button type="button" class="finish">Confirm Submission</button>
    </div>
    <script>
      const btnStep2Back = document.getElementById("btnStep2Back");
      const dataTable = document.getElementById("dataTable");
      btnStep2Back.addEventListener("click", function () {
        window.location.href = "http://127.0.0.1:5500/step2.html";
      });

      function loadSession() {
        let data = sessionStorage.getItem("formData") || {};
        data = JSON.parse(data);
        let output = "";

        output = `
          <tr>
          <th>Name</th>
          <td>${data.name}</td>
        </tr>
        <tr>
          <th>Email</th>
          <td>${data.email}</td>
        </tr>
        <tr>
          <th>Address</th>
          <td>${data.address}</td>
        </tr>
        <tr>
          <th>Contact No</th>
          <td>${data.phone}</td>
        </tr>`;

        dataTable.innerHTML = output;
      }
      loadSession();
    </script>
  </body>
</html>
  1. loadSession() Function
    • The loadSession() function is defined to load and display data from session storage.
    • It retrieves the "formData" item from session storage, which is expected to be a JSON string.
    • The code then parses the JSON data into a JavaScript object.
    • Next, it constructs an HTML table structure (inside the output variable) with rows for "Name," "Email," "Address," and "Contact No" and populates the corresponding data from the data object.
    • Finally, it sets the innerHTML of the "dataTable" table element to the generated HTML, effectively displaying the user-entered data in a tabular format.
  2. loadSession() Execution:
    • The loadSession() function is called immediately after it's defined, ensuring that the user's entered data is displayed when the page loads.

In summary, this code represents the "Review" step of a multi-step form. It retrieves user-entered data from session storage, displays it in a table, and provides a "Back Step" button for users to navigate to the previous step. However, the "Confirm Submission" button is included in the HTML but does not have its functionality implemented in the provided code.

To enhance the user experience, it's essential to add CSS styles to the HTML page for a visually appealing and organized presentation of content.

style.css

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap");

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}

body {
  background-color: #f2f2f2;
  width: 100vw;
  height: 100vh;
  display: grid;
  place-items: center;
}

.container {
  width: 600px;
  background-color: #fff;
  border: 1px solid #ccc;
  padding: 20px;
  border-radius: 5px;
}
h1 {
  font-size: 20px;
  font-weight: 500;
  margin-bottom: 20px;
  text-align: center;
  text-transform: uppercase;
}

h2 {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 15px;
  color: chocolate;
  text-transform: uppercase;
}

label {
  display: block;
  margin-bottom: 10px;
}

input[type="text"],
input[type="email"] {
  width: 100%;
  padding: 10px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-bottom: 20px;
}

button {
  padding: 10px 20px;
  font-size: 16px;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #45a049;
}

table {
  width: 100%;
  border: 1px solid #ccc;
  margin-bottom: 15px;
  border-collapse: collapse;
}

table th,
table td {
  border-bottom: 1px solid #ccc;
  padding: 10px;
  text-align: left;
  cursor: pointer;
}

table td {
  border-left: 1px solid #ccc;
}

tr:hover {
  background-color: #f1f1f1;
}

.finish {
  background-color: #fa5828;
}

.finish:hover {
  background-color: #bd3309;
}

Session storage is commonly used for storing temporary user preferences, maintaining user login status during a session, and caching data needed for the current user interaction. It provides a convenient way to work with client-side data without the need for server interactions.

List of Programs


JS Practical Questions & Answers


JS Practical Project