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 DOM Scripting By Example Adding and Removing Names Registering Names

What is the (e) parameter in the EventListener.?? I couldnt get my head around it.

What is the (e) parameter in the EventListener.?? I couldnt get my head around it. Whats the concept and why are we using it over here.? Can anyone explain in detail please.

3 Answers

The (e) parameter in the event listener is used to represent:

(a) the event object(event) and,

(b) the element you're attaching the event listener to

in that event handler. It can be used to reference various things e.g. to target a particular element in the DOM through event bubbling, and to prevent the browser's default behaviour of refreshing whenever a form is submitted.

So that means we are adding (e) as an argument , so that we can use it only for the purpose of preventing browser's default behaviour.?

(e) is added as a parameter in the event handler not as an argument, and it can also be used to select elements from the DOM with event bubbling and the DOM traversal concept which is selecting an element based on its relationship to another element within the DOM. For example:

const listItems = document.querySelector('ul');

listItems.addEventListener('click', (e) => {
    if (e.target.tagName == 'BUTTON') {
        let li = e.target.parentNode;
        let ul = li.parentNode;
        ul.removeChild('li');
    }
});
Tanner Cruiseship
Tanner Cruiseship
5,707 Points

I don't really get the difference between event objects and the this keyword.

Steven Parker
Steven Parker
231,236 Points

:bell: Mike tagged me ....

In an event handler using a conventional function, "this" is set to the event target (same as "e.target" if the parameter is "e"). But the code above uses an arrow function, and arrow functions do not set "this". So in that handler, "this" would just be the window object.

According to Mr.Steven Parker on Aug 2 'An event handler function is always given an argument when it is called. That argument is an Event object. In this case, it is being represented by "e".' How do you say its a parameter Mr.Osaro Igbinovia ..?