JavaScript event handling
listening and responding to (user) interaction (the "conversations")
Event handling with the DOM
These can happen in one of two ways:
user interaction through a keyboard, mouse or some input mechanism
including
touch
orswipe
in the case of a finger on a tablet screen
changes in the browser
e.g. the website does a
load
or thewindow
experiences aresize
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
We would essentially assign an event handler function 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**:**
For anyone who has used jQuery (a JavaScript-simplifier library):
$(element)
replaceseventTarget
on
replacesaddEventListener
...and suddenly the syntax looks very familiar :)
Using removeEventListener
removeEventListener
Instead of addEventListener
removing an event listener is simply removeEventListener
Listing the eventTypes
There exist events for the window, the mouse, the keyboard and as well as many input and output devices listed on the following page:
So, JavaScript can pick up on things like:
a browser window resizing
a mouse wheel rolling
a key press of a specific key or "any key"
a swipe on a mobile screen
Last updated