JS Purpose · Function · Scope: Simple Demos with Code
Simple Alert Message
Purpose: Show a basic alert when the button is clicked. Function: Demonstrates how JS can respond to user clicks and display a popup. Scope: Used in real life to confirm actions (e.g., “Are you sure?”).
HTML
<button id="alertBtn">Click for Alert</button>
CSS
/* Applied to the button with ID "alertBtn" */
#alertBtn {
padding: 0.6rem 1.2rem;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 4px;
}
#alertBtn:hover {
background-color: #0056b3;
}
JavaScript
const alertBtn = document.getElementById("alertBtn");
alertBtn.addEventListener("click", () => {
alert("⚡️ Hello! This is a simple alert message.");
});
Toggle Visibility of a Paragraph
Purpose: Show or hide a block of text when the button is clicked. Function: JS toggles a CSS property to hide/show content. Scope: Commonly used in FAQs, “read more” sections, dropdowns.
This paragraph is initially hidden. Click the button again to hide me.
HTML
<button id="toggleBtn">Show More ▼</button>
<p id="toggleText">
This paragraph is initially hidden. Click the button again to hide me.
</p>
CSS
#toggleBtn {
padding: 0.5rem 1rem;
background-color: #28a745;
color: #fff;
border: none;
border-radius: 4px;
}
#toggleBtn:hover {
background-color: #218838;
}
#toggleText {
margin-top: 1rem;
padding: 1rem;
border: 1px solid #ccc;
border-radius: 4px;
background-color: #f8f9fa;
display: none; /* hidden by default */
}
JavaScript
const toggleBtn = document.getElementById("toggleBtn");
const toggleText = document.getElementById("toggleText");
toggleBtn.addEventListener("click", () => {
if (toggleText.style.display === "none" || toggleText.style.display === "") {
toggleText.style.display = "block";
toggleBtn.innerText = "Show Less ▲";
} else {
toggleText.style.display = "none";
toggleBtn.innerText = "Show More ▼";
}
});
Change Box Color with Button
Purpose: Randomize a box’s background color on button click. Function: JS generates a random hexadecimal color and applies it via inline style. Scope: Used in dashboards, themes, user‐customizable widgets.
HTML
<div id="colorBox"></div>
<button id="colorBtn">Change Color</button>
CSS
#colorBox {
width: 150px;
height: 150px;
background-color: lightgray;
margin: 0 auto 1rem; /* Centers the box */
border: 2px solid #444;
border-radius: 8px;
transition: background-color 0.3s ease; /* Smooth transition */
}
#colorBtn {
padding: 0.6rem 1.2rem;
background-color: #17a2b8;
color: #fff;
border: none;
border-radius: 4px;
}
#colorBtn:hover {
background-color: #117a8b;
}
JavaScript
const colorBox = document.getElementById("colorBox");
const colorBtn = document.getElementById("colorBtn");
function getRandomHexColor() {
// Generates a random color e.g., #RRGGBB
return "#" + Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, "0");
}
colorBtn.addEventListener("click", () => {
const newColor = getRandomHexColor();
colorBox.style.backgroundColor = newColor;
colorBtn.innerText = `Color: ${newColor}`; // Update button text to show color
});
Hover-Triggered Text Change
Purpose: Change text when the user hovers over it, then revert on mouse out.
Function: Uses mouseover and mouseout events to alter text.
Scope: Helpful for tooltips, interactive labels, micro-animations.
Hover over this text!
HTML
<p id="hoverText">Hover over this text!</p>
CSS
#hoverText {
display: inline-block; /* Allows padding and border to apply correctly */
padding: 0.5rem 1rem;
font-size: 1.1rem;
color: #333;
border: 2px dashed #888;
border-radius: 4px;
transition: color 0.2s, background-color 0.2s; /* Smooth transition for hover */
cursor: pointer;
}
#hoverText:hover { /* CSS handles background/color change on hover */
color: #fff;
background-color: #ffc107;
}
JavaScript
const hoverText = document.getElementById("hoverText");
const originalHoverText = hoverText.innerText; // Store original text
hoverText.addEventListener("mouseover", () => {
hoverText.innerText = "🎉 Thanks for hovering! 🎉";
});
hoverText.addEventListener("mouseout", () => {
hoverText.innerText = originalHoverText; // Revert to original
});
Simple Email Validation
Purpose: Check if an email input matches a basic pattern when form is submitted. Function: Prevent form submission if invalid and show feedback. Scope: Used in signup forms, contact forms, newsletter subscriptions.
HTML
<form id="emailForm" novalidate>
<label for="emailInput">Enter your email:</label>
<input type="email" id="emailInput" placeholder="you@example.com" required />
<button type="submit" id="emailSubmit">Submit</button>
<p id="emailFeedback"></p>
</form>
CSS
#emailForm {
display: flex;
flex-direction: column;
max-width: 350px; /* Constrain form width */
margin: 1rem 0;
}
#emailForm label {
margin-bottom: 0.5rem;
}
#emailInput {
padding: 0.5rem;
font-size: 1rem;
border: 1px solid #ccc;
border-radius: 4px;
}
#emailSubmit {
margin-top: 1rem;
padding: 0.6rem 1.2rem;
background-color: #6f42c1;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
}
#emailSubmit:hover {
background-color: #5936a2;
}
#emailFeedback {
margin-top: 0.5rem;
font-size: 0.95rem;
}
JavaScript
const emailForm = document.getElementById("emailForm");
const emailInput = document.getElementById("emailInput");
const emailFeedback = document.getElementById("emailFeedback");
emailForm.addEventListener("submit", (e) => {
e.preventDefault(); // Prevent default form submission
const emailValue = emailInput.value.trim();
// Basic email pattern: something@something.something
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (emailPattern.test(emailValue)) {
emailFeedback.textContent = "✅ Email looks good!";
emailFeedback.style.color = "#28a745"; // Green for success
} else {
emailFeedback.textContent = "❌ Please enter a valid email address.";
emailFeedback.style.color = "#dc3545"; // Red for error
}
});
Real-Time Character Counter
Purpose: Count characters as user types and display usage/limit.
Function: JS listens to input events and updates counter.
Scope: Used in tweet boxes, feedback forms, SMS character limits.
Characters used: 0/100
HTML
<label for="messageInput">Type your message (max 100 chars):</label>
<textarea id="messageInput" rows="4" maxlength="100"></textarea>
<p>Characters used: <span id="charCount">0</span>/100</p>
CSS
#messageInput {
width: 100%; /* Full width of its container */
padding: 0.5rem;
font-size: 1rem;
box-sizing: border-box; /* Include padding and border in the element's total width and height */
border: 1px solid #ccc;
border-radius: 4px;
margin-top: 0.5rem;
resize: vertical; /* Allow vertical resizing */
}
#charCount {
font-weight: bold;
color: #333;
}
/* Style for charCount when nearing limit is handled by JS */
JavaScript
const messageInput = document.getElementById("messageInput");
const charCount = document.getElementById("charCount");
const maxLength = parseInt(messageInput.getAttribute("maxlength"), 10); // Get max length
messageInput.addEventListener("input", () => {
const currentLength = messageInput.value.length;
charCount.innerText = currentLength;
// Change color if approaching/exceeding limit
if (currentLength > maxLength * 0.9) { // If more than 90% of limit
charCount.style.color = "#dc3545"; // Red
} else if (currentLength > maxLength * 0.75) { // If more than 75%
charCount.style.color = "#ffc107"; // Orange/Yellow
}
else {
charCount.style.color = "#333"; // Default color
}
});