We have mentioned multiple times in this course the concept that "everything in JavaScript is an object".
This includes JavaScript events!
In this tutorial, you will learn how to work with JavaScript event objects. These objects are full of useful information for JavaScript developers, so having a thorough understanding of them will come in handy throughout your journey as a software engineer.
Table of Contents
You can skip to a specific section of this JavaScript event objects tutorial using the table of contents below:
- What are JavaScript Event Objects
- Selecting Event Targets Using JavaScript Event Objects
- Where to Find More Information About JavaScript Event Objects
- Final Thoughts
What are JavaScript Event Objects
To understand how JavaScript event objects work, we will first need to trigger some events.
Let's use the mouseover
event on our <p>
tags that we created in our last lesson. Here's the code we used to do that:
const paragraphs = document.querySelectorAll('p');
function mouseoverParagraph (){
console.log('You just moused over a paragraph!');
}
function paragraphListener(paragraph){
paragraph.addEventListener('mouseover', mouseoverParagraph);
}
paragraphs.forEach(paragraphListener);
Now how do JavaScript event objects come into play here?
JavaScript event objects contain useful information about an event that occurs on a webpage. They contain a TON of information. Here's an example of the event object that is generated when I mouseover
the first <p>
tag in our index.html
file:
MouseEvent {isTrusted: true, screenX: 2517, screenY: 350, clientX: 1237, clientY: 216, …}
altKey: false
bubbles: true
button: 0
buttons: 0
cancelBubble: false
cancelable: true
clientX: 1237
clientY: 216
composed: true
ctrlKey: false
currentTarget: null
defaultPrevented: false
detail: 0
eventPhase: 0
fromElement: null
isTrusted: true
layerX: 1237
layerY: 216
metaKey: false
movementX: 0
movementY: 0
offsetX: 1230
offsetY: 69
pageX: 1237
pageY: 216
path: (5) [p.p1, body, html, document, Window]
relatedTarget: null
returnValue: true
screenX: 2517
screenY: 350
shiftKey: false
sourceCapabilities: InputDeviceCapabilities {firesTouchEvents: false}
srcElement: p.p1
target: p.p1
timeStamp: 19593.655000033323
toElement: p.p1
type: "mouseover"
view: Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}
which: 0
x: 1237
y: 216
__proto__: MouseEvent
JavaScript event objects can be used to answer questions like:
- Where did the event occur on the page?
- What time did the event occur?
- What type of event is it? Is it a
click
, amouseover
, something else?
JavaScript event objects can also be used to modify the functionality of a callback function that is passed into the addEventListener
method. To do this, you need to modify the callback function so that it accepts a parameter.
More specifically, here is how we could change our callback function paragraphListener
so that it actually logs the event object to the console:
function mouseoverParagraph (event){
console.log(event);
}
Note that this event
parameter can be named whatever you like (although it is considered a best practice to use either event
or e
). As an example, here is an alternative way that you could write the previous code block:
function mouseoverParagraph (e){
console.log(e);
}
The only important caveat you need to keep in mind for accepting events into callback functions is that the event must be the first argument of the function, or else the callback function will break. In this example, if mouseoverParagraph
accepted another argument, the order should be:
function mouseoverParagraph (e, anotherArgument){
console.log(e);
console.log(anotherArgument);
}
NOT:
function mouseoverParagraph (anotherArgument, e){
console.log(e);
console.log(anotherArgument);
}
Generally, we aren't going to accept an event simply to log that entire event object to the console. We're going to actually use the data within the event object to change the performance of our function.
A very basic example of this would be to log the x and y coordinates of the event to the console. This allows the user to see exactly where on the page the event occurred.
JavaScript event objects have attributes called pageX
and pageY
that store these coordinates. Since event objects are no different than any other object in JavaScript, these attributes can be accessed using the dot operator.
Putting all of this together, here's how we could log the x and y coordinates of an event to the console using the event object:
const paragraphs = document.querySelectorAll('p');
function mouseoverParagraph (event){
console.log(`You just moused over a <p> tag at coordinate (${event.pageX}, ${event.pageY})`);
}
function paragraphListener(paragraph){
paragraph.addEventListener('mouseover', mouseoverParagraph);
}
paragraphs.forEach(paragraphListener);
Selecting Event Targets Using JavaScript Event Objects
One of the most useful functionalities of JavaScript event objects is their ability to provide information about the HTML element that the event is being performed on.
This information is stored in a child object (which just means an object within the event object) called target
.
To see this principle in action, let's select the button
item from our index.html
file:
const button = document.querySelector('button');
Next, let's create a callback function that logs the target
child object to the console:
const button = document.querySelector('button');
function logTarget(event){
console.log(event.target);
}
Finally, let's use the addEventListener
method to run the logTarget
method whenever the button is clicked:
const button = document.querySelector('button');
function logTarget(event){
console.log(event.target);
}
button.addEventListener('click', logTarget);
Now, when you click the "Click me!!!" button, the following HTML will be logged to the console:
<button class="btn">Click me!!!</button>
The target
object is very useful for creating interactive and responsive functionality in a modern JavaScript website.
Where to Find More Information About JavaScript Event Objects
Event objects are a very sophisticated component of the JavaScript programming language. We have only touched the surface of them in this tutorial.
If you ever need more information about event objects (especially what their possible properties and methods are), this page from w3schools.com is an excellent resource.
Final Thoughts
In this tutorial, you learned how to work with JavaScript event objects.
Here is a brief summary of what we covered:
- What a JavaScript event object is
- How to select an event object using a callback function
- An example of the properties and methods contained inside of a
mouseover
event object - How to select properties and attributes from an event object using the dot operator
- How to select the target of a JavaScript event using the
target
keyword