Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Can someone explain for me what the event object is?

Hi, I understand that an event is every action that happen on a web page, like mouse click, scroll, double click etc. So what is an event object? Can I think about it as a variable that contains every informations about an event that has occured?

Also I have one more question - what is an example of event handler? I understand what it is and what it does. What is an event handler in a code below?

listItem.addEventListener('click', () => {
   listItem.style.backgroundColor = "red"
})

Thank you for any answer :)

1 Answer

Jamie Reardon
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Jamie Reardon
Treehouse Project Reviewer

You are right in thinking about the event object like a variable. It is a global object that contains a list of properties and methods that you can use when manipulating the DOM with JavaScript. A good way to get some practice and strengthen your understanding of it is to play around with it in the console by checking out it's properties. Knowing this can really help you out in the future when using the event object.

An event handler is usually another name for a function that "handles" the event occured. In your code example, the ES6 Arrow function is the event handler. You can pass in the event object as the argument for this function to allow you to exploit the event object further.

For example, you can use the target property of the event object to see exactly which element triggered the event by logging it to the console:

listItem.addEventListener('click', (event) => {
  console.log(event.target);
  listItem.style.backgroundColor = "red";
});

// same as above, just using older syntax for the event handler function
listItem.addEventListener('click', function (event) {
  console.log(event.target);
  listItem.style.backgroundColor = 'red';
});

Thank you!