How Events work in Javascript
📣 Sponsor
The reason we use Javascript on frontend applications is because it can handle user events. A user event is whenever a user interacts with a webpage, which can mean anything from clicking to scrolling.
Events in Javascript are attached to a specific HTML element. That means they relate to specific tags within your HTML. This gives us a lot of flexibility with what we can do. Let's dive into how to do it.
What events does Javascript support?
Javascript supports many different events. Below are some basic events we can use:
Event | Event Description |
click | when a user clicks on the page with a mouse. |
scroll | when a user scrolls down a page. |
resize | when a user resizes the window. |
dblclick | when a user double clicks. |
hover | when a user scrolls down a page. |
mouseup, mousedown, mousemove | when a user clicks down (mousedown), releases their mouse button (mouseup), and moves their mouse while it is pressed down (mousemove). |
mouseleave, mouseout | for handling when a user moves their mouse out of an element. mouseout will only fire once, while mouseleave will fire for every div it leaves. |
touchstart, touchend, touchmove | when a user touches on a touch device (touchstart) and when they lift their finger (touchend). |
pointerdown, pointerup, pointermove | This replicates touchdown/mousedown, touchup/mouseup and touchmove/mousemove. |
pointerout, pointerleave, pointerenter | pointerout and pointerleave replicates mouseout/mouseleave. pointerenter is when the user's pointer enters a specific element. |
How do we use events?
To use an event, we need to select HTML elements first. You can learn a bit more about how to do that here. Events are attached to each HTML tag separately, which means if there are multiple buttons, we need to loop through them.
Let's start with an easy example. Say we have one button, with the id 'my-id', and we want to add a click event to it. We use the function addEventListener
, like so:
let element = document.getElementById('my-id');
element.addEventListener('click', function(e) {
// Whenever the user clicks on 'my-id', this function will run.
});
Now we have a simple function which will run when a user clicks on a button. We can attach as many events as we like to elements. Let's take another example, where we have multiple elements using querySelectorAll
. In this case, querySelectorAll
returns a NodeList which we can iterate through. You can read more about NodeLists here.
let elements = document.querySelectorAll('.button');
elements.forEach(function(item) {
item.addEventListener('click', function(e) {
// Whenever the user clicks on this particular .button, this function will run.
});
item.addEventListener('hover', function(e) {
// Whenever the user hovers over this particular .button, this function will run.
});
})
Events
You may have noticed that when we call our functions, we mention a variable called e - you may also see it written as event or evt.
// ...
// Notice how we have function(e)..
item.addEventListener('hover', function(e) {
// ...
When we add our event to an HMTL tag, there is a lot of information about that event that your browser tracks. Javascript passes all of that into a variable, and we can access that through e. If you want a thought experiment about how this works, essentially Javascript runs the function we define, and passes in all the event data into the variable, a bit like this:
// Notice how we have function(e)..
item.addEventListener('hover', function(e) {
// ...
// The function(e) may be run like this in Javascript, where all the event data is passed into the place of the e.
// That means we can access all this data when we run our events.
hoverCallbackFunction({ "all-event-data-goes-here" })
You can use this variable for all sorts of things. For example, on click events, we can get the position where the user clicked on the page:
document.body.addEventListener('click', function(e) {
let xCoord = e.pageX;
let yCoord = e.pageY;
document.getElementById('coordinates').textContent = `You clicked on X: ${xCoord}, Y: ${yCoord}!`;
});
Although we won't cover all the things that are contained within the e variable, it is good to be aware that this contains very useful information about what your user is doing. They can all be accessed by saying e.variable. Here are a few:
- e.target - the HTML element the event was performed on top of.
- e.pageX - the X coordinate where the user performed the event, relative to the page.
- e.pageY - the Y coordinate where the user performed the event, relative to the page.
- e.clientX - the X coordinate where the user performed the event, relative to the viewport/window.
- e.clientY - the Y coordinate where the user performed the event, relative to the viewport/window.
Since the function for addEventListener
is ran every time an event is done, we can use this data to calculate what a user is doing. For example, doing what we did before, with mousemove
, means we have live coordinates of the user's mouse position:
document.body.addEventListener('hover', function(e) {
let xCoord = e.pageX;
let yCoord = e.pageY;
document.getElementById('coordinates').textContent = `You hovered over X: ${xCoord}, Y: ${yCoord}!`;
});
Adding the same function to multiple event handlers
Imagine you want to the same event for hover and click. You can do this easily with arrays, by doing something like this:
[ 'click', 'hover' ].forEach(function(eventType) {
// this forEach will run twice, once for click and once for hover
// We can access the keywords 'click' and 'hover' through the 'eventType' variable
document.body.addEventListener(eventType, function(e) {
// Our event function goes here
});
})
More Tips and Tricks for Javascript
- How to select HTML elements in Javascript
- Inserting an Item into an Array at a Specific Index in Javascript
- Changing HTML Classes and Attributes in Javascript
- Javascript innerHTML
- Javascript Errors
- Checking if a value is a number in Javascript with isNaN()
- How does the Javascript logical AND (&&) operator work?
- How JSON works in Javascript
- Using an Array as Function Parameter in JavaScript
- How does the Javascript logical OR (||) operator work?