Reference Material For Hackathon
Writing HTML easily
Because backticks allow multiple lines and variable insertion, they are the standard way to
generate HTML "blocks" in JavaScript
// Example from your receipt code
let html = `
<div class="box">
<h4>${[Link]}</h4>
<span>$${[Link]}</span>
</div>
`;
Local Storage
Description
Local storage is a part of the HTML Web Storage API that allows web applications to store
data locally within a user's browser. Unlike cookies, this data is never transferred to the
server and has a much larger capacity—typically 5MB per domain
Basic Operations
You can manage data using the following standard methods:
Store data: Use setItem(key, value) to save information.
[Link]("username", "JohnDoe");
Retrieve data: Use getItem(key) to get the value associated with a key
let name = [Link]("username");
Remove an item: Use removeItem(key) to delete a specific pair.
[Link]("username");
Clear all data: Use clear() to empty all local storage for the domain
[Link]();
$ - used for Interpolation that Javascript needs to referh
Application of local storage to - generate receipt
JSON stands for JavaScript Object Notation. It is a lightweight, text-based format used to
store and transport structured data, typically between a web server and a client.
JSON has become the "universal language" of the web.
[Link](): Object to String (used for saving data).
[Link](): String to Object (used for reading data).
<script>
function generateReceipt() {
const name = [Link]('itemName').value;
const price = [Link]('itemPrice').value;
if (!name || !price) return alert("Please enter all details");
// 1. Create a data object
const receipt = {
name: name,
price: price,
date: new Date().toLocaleDateString()
};
// 2. Save to local storage (must stringify first)
[Link]('recentReceipt', [Link](receipt));
// 3. Display the receipt
displayReceipt();
}
function displayReceipt() {
// 4. Retrieve and parse from local storage
const savedData = [Link]([Link]('recentReceipt'));
}
}
// Load receipt if it exists when the page is refreshed
[Link] = displayReceipt;
</script>
Session Storage
Using sessionStorage is almost identical to localStorage, but with one major difference: the
data is wiped as soon as the tab or window is closed.
It is perfect for sensitive data or temporary actions that shouldn't persist after the user leaves
your site.
Example of session storage
<script>
function saveData() {
// 1. Get values from inputs
const nameValue = [Link]('userName').value;
const jobValue = [Link]('userJob').value;
// 2. Create object and save to Session Storage
const info = { name: nameValue, job: jobValue };
[Link]('myUser', [Link](info));
// 3. Show the data
showData();
}
function showData() {
// 1. Get string from storage and turn back into object
const stored = [Link]('myUser');
if (stored) {
const data = [Link](stored);
// 2. Put values into the spans
[Link]('displayName').textContent = [Link];
[Link]('displayJob').textContent = [Link];
// 3. Make the result box visible
[Link]('result').[Link] = "block";
} else {
// Hide if empty
[Link]('result').[Link] = "none";
}
}
function clearData() {
[Link]('myUser');
showData();
}
// Run when page opens/refreshes
[Link] = showData;
</script>
2) Filter Information from an Array
<script>
// 1. Data Array
const items = [
{ id: 1, name: "Apple" },
{ id: 2, name: "Banana" },
{ id: 3, name: "Orange" },
{ id: 4, name: "Pineapple" },
{ id: 5, name: "Grape" }
];
// 2. Main Search Function
function handleSearch() {
const query = [Link]('searchInput').[Link]();
// Filter the array
const filtered = [Link](item => {
// Check if item name contains the search text
return [Link]().includes(query);
});
renderList(filtered);
}
// 3. Display Function
function renderList(list) {
const container = [Link]('results');
[Link] = ""; // Clear old results
if ([Link] === 0) {
[Link] = "<p>No matches found.</p>";
return;
}
[Link](item => {
const div = [Link]('div');
[Link] = [Link];
[Link](div);
});
}
</script>
4. Adding Items to Cart/ Clear Cart
<script>
// Load existing cart or initialize empty array
let cart = [Link]([Link]('myCart')) || [];
// Run immediately on page load to show saved items
[Link]('DOMContentLoaded', renderCart);
function addToCart(name, price) {
const existingItem = [Link](item => [Link] === name);
if (existingItem) {
[Link] += 1;
} else {
[Link]({ name, price, quantity: 1 });
}
updateStorageAndUI();
}
function clearCart() {
cart = [];
updateStorageAndUI();
}
function updateStorageAndUI() {
[Link]('myCart', [Link](cart));
renderCart();
}
// Render function executes only after HTML document is completely loaded.
function renderCart() {
const cartList = [Link]('cart-items-list');
const totalPriceElement = [Link]('cart-total-price');
[Link] = '';
let total = 0;
[Link](item => {
const li = [Link]('li');
[Link] = `${[Link]} x${[Link]} - $${[Link] *
[Link]}`;
[Link](li);
total += [Link] * [Link];
});
[Link] = total;
}
</script>