Common JS Patterns
Check user input before submit — empty fields, email format, minimum length. Show errors next to fields.
Form validation
Check user input before submit — empty fields, email format, minimum length. Show errors next to fields.
Real-life example: A bouncer at a club checks ID before entry — form validation checks data before it goes to the server.
document.querySelector("#signup-form").addEventListener("submit", (e) => {
e.preventDefault();
const email = document.querySelector("#email").value.trim();
const error = document.querySelector("#email-error");
if (!email.includes("@")) {
error.textContent = "Please enter a valid email.";
return;
}
error.textContent = "";
alert("Form OK — ready to send!");
});Toggle menu (mobile nav)
A hamburger button adds or removes a class on the nav to show or hide links on small screens.
Real-life example: A folding map — tap to open full view, tap again to fold it back into your pocket.
const menuBtn = document.querySelector("#menu-btn");
const nav = document.querySelector("#main-nav");
menuBtn.addEventListener("click", () => {
nav.classList.toggle("open");
menuBtn.setAttribute(
"aria-expanded",
nav.classList.contains("open")
);
});Counter
Track a number with + and − buttons. Update the screen with textContent each click.
Real-life example: A cricket scoreboard — each run adds one; the display always shows the latest total.
let count = 0;
const display = document.querySelector("#count");
document.querySelector("#plus").addEventListener("click", () => {
count++;
display.textContent = count;
});
document.querySelector("#minus").addEventListener("click", () => {
count--;
display.textContent = count;
});Accordion idea
Only one panel open at a time — click a heading to show its content and hide others.
Real-life example: FAQ on a help page — open one question's answer; closing others keeps the page tidy.
document.querySelectorAll(".accordion-btn").forEach((btn) => {
btn.addEventListener("click", () => {
const panel = btn.nextElementSibling;
const isOpen = panel.classList.contains("open");
document.querySelectorAll(".accordion-panel").forEach((p) => {
p.classList.remove("open");
});
if (!isOpen) panel.classList.add("open");
});
});