JavaScript event handling
listening and responding to (user) interaction (the "conversations")
The second that a user lands on a webpage on a browser, the JavaScript engine sits there "listening" for the user to interact with that webpage and that webpage's components, either through a:
keypress (or combination of keypresses)
mouse click
mouse move
swipe or touch or shake (if using a mobile device)
resize of the browser
...and anything that has to do with interaction!
There even exist event listeners for when the page loads, so that "things" "can happen" when the user refreshes the browser on that page!
Using on...
events
on...
eventsEach querySelector
has properties commonly called listeners that
detect (listen to) any events, such as:
a mouse-click (
click
)a change in browser window size (
resize
)a page load (
load
)
in order to handle (respond to) them
the detection gets prefixed with
on
so that for anyclick
event, the property is calledonclick
We would essentially assign an event handler function (turnButtonGreen()
in the example below) that will happen when an event triggers:
Generalizing the last line above:
Using addEventListener
addEventListener
Another way of writing the event handler uses the addEventListener(eventType, callback)
format:
load
versus DOMContentLoaded
load
versus DOMContentLoaded
A subtle difference exists between the eventType
s of load
and DOMContentLoaded
:
load
waits for the entire page to load: images, stylesheets, scripts, etc.DOMContentLoaded
waits only for the HTML to load (ignoring the other non-DOM things)
One application of this involves having a "loading" image while the page loads, which then changes into another image after the DOM has settled:
Using removeEventListener
removeEventListener
Instead of addEventListener
removing an event listener is simply removeEventListener
A list of all eventType
s
eventType
sThere exist events for the window, the mouse, the keyboard and as well as many input and output devices listed on the following page:
Last updated