Skip to content

Instantly share code, notes, and snippets.

@prof3ssorSt3v3
Created November 21, 2022 21:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prof3ssorSt3v3/7ba75cf67acad8ca1d00bf21e32d8547 to your computer and use it in GitHub Desktop.
Save prof3ssorSt3v3/7ba75cf67acad8ca1d00bf21e32d8547 to your computer and use it in GitHub Desktop.
Sample localStorage page from class with ability to add or remove petnames
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Web Storage</title>
<link rel="stylesheet" href="./storage.css" />
<script src="./storage.js" type="module"></script>
</head>
<body>
<header>
<h1>LocalStorage &amp; SessionStorage</h1>
<h2>Web Storage API</h2>
</header>
<nav>
<form>
<input type="text" id="txtPet" />
<button id="btnPet">Add Pet Name</button>
</form>
</nav>
<main>
<!-- list of pet names -->
</main>
</body>
</html>
*,
*::before,
*::after {
box-sizing: border-box;
padding: 0;
margin: 0;
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans',
'Helvetica Neue', sans-serif;
font-weight: 100;
}
html {
font-size: 20px;
color-scheme: dark light;
}
header,
nav,
main {
padding: 1rem 4rem;
margin: 0 0 1rem 0;
}
header {
color: cornsilk;
background-color: #333;
border-bottom: 1px solid cornflowerblue;
position: relative;
}
header::after {
/* build a triangle in the top right corner */
border: 3rem solid coral;
border-left-color: transparent;
border-bottom-color: transparent;
position: absolute;
content: '';
right: 0px;
top: 0px;
display: block;
z-index: 10;
height: 1px;
width: 1px;
overflow: hidden;
}
h1 {
margin-bottom: 1rem;
font-weight: 300;
color: coral;
}
input {
font-size: 1rem;
padding: 0.2rem 1rem;
caret-color: cornflowerblue;
margin: 0 1rem 0 0;
}
button {
font-size: 1rem;
padding: 0.2rem 2rem;
cursor: pointer;
}
p {
font-size: 1.2rem;
color: cornsilk;
cursor: pointer;
padding: 0.5rem 1rem;
font-variant: small-caps;
transition: font-size 0.3s linear, background-color 0.3s linear;
}
p:hover {
background-color: #333;
}
.buhbye {
font-size: 0.1rem;
}
//Web Storage is like a local Backup of the current state of a website
const key = 'steve-petnames-310';
//Single Source of Truth
/*
localStorage.getItem(key)
setItem(key, value) - the one you use 90% of the time
removeItem(key)
clear()
key(index)
*/
let petnames = []; //default value
document.addEventListener('DOMContentLoaded', () => {
// localStorage.setItem(key, 'Akshay');
let store = localStorage.getItem(key);
//this is the ONLY time I will call getItem... when the page loads
console.log(store);
if (store === null) {
//nothing in localStorage yet with a matching key
//JSON .stringify() .parse()
let str = JSON.stringify(petnames);
localStorage.setItem(key, str);
} else {
//we have old data in localStorage that we can use
//only if it is an Array though
let obj = JSON.parse(store);
if (Array.isArray(obj)) {
//if it is an array then we want to use it
petnames = obj;
} else {
//overwrite with the default value
localStorage.setItem(key, JSON.stringify(petnames));
}
//turn the string into an object (Array).
//replace the empty array with the value
}
// let btn = document.getElementById('btnPet');
// btn.addEventListener('click', addPet);
let frm = document.querySelector('nav > form');
frm.addEventListener('submit', addPet);
buildContent();
let main = document.querySelector('main');
main.addEventListener('click', removePet);
});
function delay(tim = 500) {
return new Promise((resolve) => {
setTimeout(resolve, tim);
});
}
async function removePet(ev) {
// check that it was a <p> clicked
// get the textContent from the <p>
// use array.filter to remove the petname from petnames
// call setItem to update that list
// call buildContent again
let p = ev.target;
if (p.localName === 'p') {
p.className = 'buhbye';
let txt = p.textContent;
petnames = petnames.filter((name) => name !== txt);
//if name ! = = txt then the function returns true. We want to keep the non-matching name
localStorage.setItem(key, JSON.stringify(petnames));
await delay(400).then(buildContent);
}
}
function buildContent() {
let main = document.querySelector('main');
main.innerHTML = petnames.map((name) => `<p>${name}</p>`).join('');
}
function addPet(ev) {
ev.preventDefault(); //stop the submit of the form
let name = document.getElementById('txtPet');
let val = name.value.toLowerCase();
val = val.trim();
if (val !== '') {
petnames.push(val);
name.value = '';
name.focus(); //return the focus to the emptied input element
buildContent();
localStorage.setItem(key, JSON.stringify(petnames));
//localStorage is always a REPLACE operation, not an EDIT
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment