HTML5
Local & Session Storage
Persist data in the browser with the Web Storage API.
By EZ4Code Team
storageweb-storage
Code
// Store a value (strings only; serialize objects)
localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme"); // "dark"
// Objects need JSON
const user = { name: "Alice", age: 30 };
localStorage.setItem("user", JSON.stringify(user));
const restored = JSON.parse(localStorage.getItem("user"));
// Remove one key or everything
localStorage.removeItem("theme");
localStorage.clear();
// Listen for changes in other tabs
window.addEventListener("storage", e => {
console.log(e.key, "changed from", e.oldValue, "to", e.newValue);
});
// Session storage clears when the tab closes
sessionStorage.setItem("token", "abc");Explanation
localStorage persists string key-value pairs with no expiration, while sessionStorage clears when the tab closes. Both share a synchronous API of setItem, getItem, and removeItem. The storage event fires in other tabs when data changes, enabling lightweight cross-tab sync.
More HTML5 Snippets
Semantic Elements
Structure a page with header, nav, main, article, and footer.
Form Input Types
Use native HTML5 input types, validation, and datalist.
Canvas Basics
Draw shapes, lines, and text on a 2D canvas.
Video & Audio
Embed media with multiple sources and control playback.
Geolocation
Get the user's position and watch for changes.
Drag and Drop
Accept dropped files with the Drag and Drop API.