Today we moved deeper into JavaScript events, timing functions (setTimeout, setInterval) and async programming with fetch.
We learned how to add event listeners to HTML elements.
<button id="clickMeButton">ClickMe</button>
<script>
document.getElementById("clickMeButton").addEventListener("click", function() {
alert("Button clicked!");
});
</script><div id="message" style="border: 1px solid black; align-content: center;">check this</div>
<script>
document.getElementById("message").addEventListener("mouseover", function() {
this.style.color = "red";
this.textContent = "Mouse over the message!";
this.style.backgroundColor = "yellow";
});
document.getElementById("message").addEventListener("mouseout", function() {
this.style.color = "black";
this.textContent = "check this";
this.style.backgroundColor = "white";
});
</script><input type="text" id="inputField" placeholder="Type something...">
<script>
document.getElementById("inputField").addEventListener("keydown", function() {
console.log("Key pressed in input field, " + this.value);
});
</script>Runs once after a delay.
<script>
console.log("Start");
setTimeout(() => {
console.log("Runs after 2 seconds");
}, 2000);
console.log("End");
</script>Runs repeatedly at a given interval.
<script>
console.log("Start");
setInterval(() => {
console.log("Runs every 2 seconds");
}, 2000);
console.log("End");
</script>We explored async/await for making API calls.
async function getData() {
let response = await fetch("https://en.wikipedia.org/api/rest_v1/page/summary/Puneeth_Rajkumar");
let data = await response.json();
console.log(data);
}
getData();Another example that updates the DOM:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wikipedia Fetch Activity</title>
</head>
<body>
<h2>Wikipedia Summary 📖</h2>
<div id="info"></div>
<script>
async function getData() {
let response = await fetch("https://en.wikipedia.org/api/rest_v1/page/summary/Aamir_Khan");
let data = await response.json();
document.getElementById("info").innerHTML = `
<h3>${data.title}</h3>
<p>${data.extract}</p>
`;
}
getData();
</script>
</body>
</html>-
Counter using Click Event → Button click should increase a counter on the page.
-
Mouseover with Image Swap → On
mouseoverandmouseout, swap an image. -
Keydown Events for Colors → Change background color of the body based on key pressed:
R→ RedG→ GreenB→ Blue
-
Wikipedia Fetch → Choose your own celebrity, fetch data from Wikipedia API, and also display their image if available.
-
setTimeout Flag Colors → Change the background color every 3 seconds (Orange → White → Green).
-
setInterval Even/Odd Printing → Print even and odd numbers alternately in the console every 2 seconds.
✅ Day 16 Summary: Learned about event handling, timing functions, and async/await. Homework combines interactivity with async fetch requests.