Bringing the Interface to Life
An event is a signal from the browser that something has happened — a click, a page load, a mouse movement. Your JavaScript code can " listen " for these signals and react to them.
Three Ways to Assign a Handler
1. HTML Attribute (Not Recommended)
<button onclick="alert('Clicked!')">Click me</button>
This mixes HTML and JavaScript logic and is considered bad practice today.
2. DOM Property
elem.onclick = function() {
alert('Clicked!');
};
Simple, but has a fatal flaw: you can only assign one handler. If you write elem.onclick = ... a second time, it overwrites the first one completely.
3. addEventListener (The Modern Standard)
function greetUser() {
alert('Hello, user!');
}
function logAnalytics() {
console.log('Click event recorded.');
}
elem.addEventListener('click', greetUser);
elem.addEventListener('click', logAnalytics); // Both handlers work!
Tip
Always prefer addEventListener. It allows you to attach as many handlers as you need to a single event, making your code modular and easy to manage. You can also remove a specific handler later with removeEventListener.