Site icon StakeDesigner

Exploring JavaScript Local Storage vs Session Storage vs Cookie

JavaScript Local Storage vs Session Storage vs Cookie

In the world of web development, managing client-side data efficiently is crucial for building robust and user-friendly applications. Local Storage, Session Storage, and Cookies are three commonly used mechanisms for storing data on the client side. Each has its unique features, use cases, and limitations. In this article, we’ll dive into the differences between Local Storage, Session Storage, and Cookies, and discuss when to use each one.

Local Storage vs. Session Storage vs. Cookies

Introduction to Client-Side Storage

Before we delve into the specifics of Local Storage, Session Storage, and Cookies, let’s understand the basic concepts of client-side storage.

Cookies:

Cookies are small pieces of data stored in the browser. They are sent with every HTTP request to the server, making them suitable for persistent data that needs to be sent back and forth between the client and server.

Cookies have been a staple of web development for a long time. They are small pieces of data stored in the browser and sent with every HTTP request to the server. Cookies are commonly used for various purposes, such as maintaining user sessions, tracking user behavior, and storing user preferences.

Local Storage:

Local Storage provides a way to store key-value pairs in the browser with no expiration date. The data persists even after the browser is closed, making it ideal for storing long-term preferences or user settings.

Local Storage provides a way to store key-value pairs in the browser with no expiration date. This means that the data stored in Local Storage persists even after the browser is closed and can be accessed by any page from the same origin. It’s an excellent choice for storing long-term preferences or user settings that should remain consistent across multiple sessions.

Session Storage:

Session Storage is similar to Local Storage, but the data is cleared when the session ends (i.e., when the browser is closed). It’s useful for storing temporary data that should be available only during the current browsing session.

Similar to Local Storage, Session Storage allows you to store data in the browser, but with one crucial difference: the data stored in Session Storage is cleared when the browser session ends. This means that the data is only available for the duration of the page session, making it suitable for storing temporary information that should not persist across sessions.

Local Storage vs Session Storage vs Cookie

JavaScript Local Storage vs Session Storage vs Cookie Differences and Use Cases

Now, let’s explore the differences between Local Storage, Session Storage, and Cookies, along with examples of when to use each one.

Local Storage:

// Setting data in Local Storage
localStorage.setItem('username', 'JohnDoe');

// Retrieving data from Local Storage
const username = localStorage.getItem('username');
console.log(username); // Output: JohnDoe

JavaScript Project Todo-List with JavaScript Local Storage

In the realm of web development, creating a todo list application is a quintessential project for beginners. It encapsulates the core concepts of HTML for structure, CSS for styling, and JavaScript for interactivity. In this article, we’ll walk through the development of a basic todo list application utilizing these technologies.

Project Overview

Our todo list application will have the following features:

  1. Ability to add new tasks.
  2. Ability to edit existing tasks.
  3. Ability to delete tasks.
  4. Data persistence using local storage.

Project Structure

Let’s dissect the structure of our project:

HTML

<div class="todo-list-container">
    <form class="todo-list-header">
        <input id="text-input" type="text" value="">
        <button type="submit" id="text-add">Add</button>
    </form>
    <div id="inputerro"></div>
    <div class="todo-content">
        <ul>

        </ul>
    </div>
</div>

This is the HTML structure of our application. It consists of a form to input new tasks, a container to display existing tasks, and buttons for editing and deleting tasks.

Styling with CSS

.todo-list-container {
  width: 600px;
  margin: 0 auto;
  font-family: Arial, sans-serif;
}

.todo-list-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.todo-list-header input[type="text"] {
  width: calc(100% - 70px);
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 5px;
  outline: none;
}

.todo-list-header button {
  padding: 8px 15px;
  border: none;
  border-radius: 5px;
  background-color: #4CAF50;
  color: white;
  cursor: pointer;
}

.todo-list-header button:hover {
  background-color: #45a049;
}

.todo-content ul {
  list-style-type: none;
  padding: 0;
}

.todo-content li {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  display: flex;
  
}

.todo-content li input[type="text"] {
  width: calc(100% - 70px);
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 3px;
  outline: none;
}

.todo-content li button {
  margin-left: 5px;
  padding: 5px 10px;
  border: none;
  border-radius: 3px;
  background-color: #f44336;
  color: white;
  cursor: pointer;
}

.todo-content li button.edit {
  background-color: #2196F3;
}

.todo-content li button:hover {
  background-color: #d32f2f;
}

.todo-content li button.edit:hover {
  background-color: #1976D2;
}
.todo-content li .button-container {
  display: flex;
  align-items: center;
}

.todo-content li .button-container button {
  margin-left: 5px;
}

.todo-content li button {
  padding: 5px 10px;
  border: none;
  border-radius: 3px;
  background-color: #f44336;
  color: white;
  cursor: pointer;
}

.todo-content li button.edit {
  background-color: #2196F3;
}

.todo-content li button:hover {
  background-color: #d32f2f;
}

.todo-content li button.edit:hover {
  background-color: #1976D2;
}

We’ve applied some basic styling to our elements to enhance their appearance. The CSS rules define the layout, colors, and styles of various components such as input fields, buttons, and task items.

Interactivity with JavaScript

const addButton = document.getElementById("text-add");
const todoList = document.querySelector(".todo-content ul");

function addTodo() {
    var textinput = document.getElementById("text-input").value;
    if (textinput != "") {
        const newitem = document.createElement("li");
        newitem.innerHTML = `<input type="text" disabled  value="${textinput}">
           <div class="button-container">
        <button class="edit">Edit</button>
        <button class="delete">Delete</button>
      </div>`
        todoList.appendChild(newitem);
        document.getElementById("text-add").value = "";
        let todos = JSON.parse(localStorage.getItem("textinput")) ?? [];
        console.log(todos);
        todos.push(textinput);
        localStorage.setItem("textinput", JSON.stringify(todos))
    }
}

let displayData = () => {
    let todos = JSON.parse(localStorage.getItem("textinput")) ?? [];
    let finalData = "";
    todos.forEach((element, i) => {
        finalData += `<li><input type="text" disabled  value="${element}">
           <div class="button-container">
        <button onclick="updateTodoInStorage(${i})" class="edit">Edit</button>
        <button onclick="removeData(${i})" class="delete">Delete</button>
      </div></li>`;
    });
    todoList.innerHTML = finalData;
}

let removeData = (index) => {
    let todos = JSON.parse(localStorage.getItem("textinput")) ?? [];
    alert(index);
    todos.splice(index, 1);
    localStorage.setItem("textinput", JSON.stringify(todos))
}




function deleteTodo(event) {
    const listItem = event.target.closest("li");
    todoList.removeChild(listItem);
    // removeTodo(listItem.querySelector("input[type='text']").value);
}

function editTodo(event) {
    const listItem = event.target.closest("li");
    const textInput = listItem.querySelector("input[type='text']");
    textInput.disabled = !textInput.disabled;
    if (textInput.disabled) {
        event.target.textContent = "Edit";
    } else {
        event.target.textContent = "Save";
    }
}

function updateTodoInStorage(index) {
    console.log("Index:", index);
    let todos = JSON.parse(localStorage.getItem("textinput")) ?? [];

    const listItems = Array.from(todoList.children);
    console.log(listItems);
    const updatedTodo = listItems[index].querySelector("input[type='text']").value;

    todos[index] = updatedTodo;
    console.log("Updated Todos:", todos);

    localStorage.setItem("textinput", JSON.stringify(todos));

}



todoList.addEventListener("click", function (event) {
    if (event.target.classList.contains("edit")) {
        editTodo(event);
    } else if (event.target.classList.contains("delete")) {
        deleteTodo(event);
    }
});

addButton.addEventListener("click", function (e) {
    e.preventDefault();
    addTodo();
});

displayData();

The JavaScript code provides the functionality to our todo list application. Let’s break down the key functionalities:

Session Storage:

// Setting data in Session Storage
sessionStorage.setItem('token', 'abc123');

// Retrieving data from Session Storage
const token = sessionStorage.getItem('token');
console.log(token); // Output: abc123

Cookies:

// Setting a cookie
document.cookie = 'username=JohnDoe; expires=Fri, 31 Dec 9999 23:59:59 GMT';

// Retrieving cookies
const cookies = document.cookie.split(';');
console.log(cookies); // Output: ["username=JohnDoe"]

Conclusion

In conclusion, Local Storage vs Session Storage vs Cookie are all valuable tools for managing client-side data in web applications. Choosing the right storage mechanism depends on factors such as data persistence requirements, security considerations, and storage capacity.

Exit mobile version