Introduction
Web pages often feel static and boring without interaction. Making buttons clickable, forms respond, or images change when you hover adds life to websites. JavaScript is the tool that brings these actions to life on web pages.
Jump into concepts and practice - no test required
Imagine a puppet show where the puppeteer controls the puppets to move and talk when the audience claps or shouts. JavaScript is like the puppeteer, watching for audience actions and making the puppets respond instantly.
┌───────────────┐ listens for ┌───────────────┐
│ User Action │────────────────────────▶│ Event Listener│
└───────────────┘ └──────┬────────┘
│ runs code
▼
┌─────────────────┐
│ JavaScript Code │
└────────┬────────┘
│ changes
▼
┌─────────────────┐
│ Web Page (DOM) │
└─────────────────┘const button = document.querySelector('button'); button.addEventListener('click', () => { const message = document.querySelector('#message'); message.textContent = 'You clicked the button!'; });
myBtn in JavaScript?addEventListener and the event name is 'click', not 'onclick'.function() { alert('Clicked!'); } is correct. Directly calling alert('Clicked!') passes the result, not the function.const btn = document.getElementById('btn');
btn.addEventListener('click', () => {
btn.textContent = 'Clicked!';
});textContent is the correct property to change the visible text inside an element.box when clicked:const box = document.getElementById('box');
box.addEventListener('click', changeColor);
function changeColor() {
box.style.background = 'blue';
}backgroundColor, not background.text each time it is clicked. Which code snippet correctly implements this behavior?display is 'none' and switch it to 'block', else set to 'none'.