A user interacts with a web page through several actions that may include, clicking a button, scrolling down a page or keying in a value. It is important to understand and take note of these actions to determine how to respond to them.
What's a DOM event?
DOM (Document Object Model) events are actions that occur as a result of the user action or as a result of state change of the elements of a DOM tree.
Wikipedia
In a nutshell, it is the program's interpretation of a users action on elements of a DOM.
Examples of DOM events and their triggers.
click
- when a user clicks on an element.
keydown
- when a user presses a key.
keyup
- when a user releases a key.
mouseup
- when a mouse button is released.
mousedown
- when a mouse button is pressed.
mousemove
- when a mouse pointer moves.
scroll
- when a user scrolls an element.
focus
- when an element has received focus.
blur
- when an element loses focus.
load
- when a page finishes loading.
beforeunload
- when a page is closed.
Touch interaction events
touchstart
- when a finger starts touching a screen.
touchmove
- when a finger is moved while touching the screen
touchend
- when a finger stops touching a screen
How do we respond to DOM events?
Since you have an idea of some of the events that might be triggered, you can move ahead to listen for this events. addEventListener()
is an inbuilt javascript method used to listen for events. It takes two parameters, the event, and a callback function. The latter is where you define how you want to respond to an event.
Default behaviour
Events in javascript have a default behaviour that may hinder your intended response to the event. Imagine a scenario where you intend to perform a computation on form data before submitting. The submit event will automatically submit this the data when triggered. To prevent this default behaviour, you can call event.preventDefault()
in the callback function of an event listener.
Done for the day
Day 85
Top comments (0)