Elements in a web page emit all kinds of "events", for example when a button is clicked it "fires" a "click" event. We can use these events to do things with special javascript functions called event handlers.
Event handlers, which are just javascript functions to be called on some event, can be connected to events using a function on element objects called addEventListener
.
For example, you can create an event handler for button clicks that alerts a message like so:
// get the button element
var button = document.querySelector('button');
// create an event handler
function buttonClicked(event) {
event.preventDefault() // supresses the event's default behavior
alert('Hello World!');
}
// add your event listener
button.addEventListener('click', buttonClicked);
Three steps to creating event listeners:
var button = document.querySelector('button');
)function buttonClicked(event) {...}
)button.addEventListener('click', buttonClicked);
)