Lecture
Demo and Notes
💡 JavaScript Functions, Events & DOM Demo
1. Functions in JavaScript
Concept: A reusable block of code that performs a task.
function greet(name) {
alert("Hello, " + name + "!");
}
2. Click Event
Concept: React to a user clicking a button using onclick.
function sayHello() {
alert("Hello from JavaScript!");
}
3. DOM Manipulation: Change Text
Concept: Use JavaScript to change page content.
Original Text
function changeText() {
document.getElementById("textPara").textContent = "Text changed!";
}
4. Mouse Events: Hover to Change Color
Concept: React to mouse entering/leaving an element.
function changeColor() {
document.getElementById("hoverBox").style.backgroundColor = "coral";
}
function resetColor() {
document.getElementById("hoverBox").style.backgroundColor = "skyblue";
}
5. Input Event: Live Update
Concept: Capture and display user input in real time.
Waiting for input…
function updateLiveText() {
const val = document.getElementById("liveInput").value;
document.getElementById("liveResult").textContent = val;
}
6. Add Item to List
Concept: Dynamically create and add HTML elements.
function addItem() {
const text = document.getElementById("itemInput").value;
const li = document.createElement("li");
li.textContent = text;
document.getElementById("itemList").appendChild(li);
}
7. Toggle Visibility
Concept: Show/hide elements using style changes.
🎉 Hello there!
function togglePara() {
const p = document.getElementById("hiddenPara");
p.style.display = (p.style.display === "none") ? "block" : "none";
}
8. Counter (State + DOM)
Concept: Use variables to track and display changing values.
0
let count = 0;
function increment() {
count++;
document.getElementById("counter").textContent = count;
}
function reset() {
count = 0;
document.getElementById("counter").textContent = count;
}