JavaScript DOM event handling
// updated 2025-11-09 15:09
Events consist of happenings that occur either by user interaction with the interface (i.e. the webpage) or some programmed action (e.g. a page reload as new data comes in).
User interactions usually happen in the form of a:
- keypress (or a combination of keystrokes)
- mouse
click - mouse
move swipeortouchorshake(on a mobile device)resizeorload(of a browser window)
Using on- events
Each querySelector has properties commonly called listeners that
- detect (i.e. "listen for") any events as listed above
- handle (i.e. "respond to") any of those events
We can create an event listener with the following template:
let element = document.querySelector('.whatever')
// event handler
function handleEvent() {
// change the element in some way, e.g.
element.style.backgroundColor = 'green'
element.style.color = 'white'
}
// event listener
element.onclick = handleEventThe event listener (detector) gets assigned an event handler (a function), so that the function gets called whenever the listener detects a specific event!
addEventListener
We can also write the last line in the above example like this:
element.addEventListener("click", handleEvent)Note the absence of the on in the first argument!
In general, this would have the syntax of:
element.addEventListener(type, handler)Although addEventListener seems like a much longer notation, it allows us to assign multiple event listeners for each element.
removeEventListener
The addEventListener way also provides a "symmetrical syntax" for the removeEventListener method:
element.removeEventListener(type, handler)Why would we remove an event listener?
Sometimes, when objects on a web page are no longer visible (such as a newly-closed modal/pop-up window), we no longer wish to have those objects monitored for events. (It cancels out its corresponding call to addEventListener.)
Further reading
- javascript.info (a list of all the UI event types)