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

Peter Larson
Peter Larson
6,412 Points

In the event listener, what is the "e" parameter?

I'm not sure what the "e" parameter is in this code

const form = document.getElementById('registrar');
const input = form.querySelector('input');

form.addEventListener('submit', (e) => {
  e.preventDefault();
  const text = input.value;
  input.value = "";
  const ul = document.getElementById('invitedList');
  const li = document.createElement('li');
  li.textContent = text;
  ul.appendChild(li);
});

mdn says that "submit" is the type and "e" is the listener, but we're writing a whole function into this and calling it "e", but "e" is also called on the next line. Additionally, arrow syntax in this situation isn't the same as was taught in the previous video that explained how that works, so I'm not following. I can type along with the example here, but I don't fully understand what I'm typing out.

1 Answer

Steven Parker
Steven Parker
231,271 Points

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".

There are many properties and methods that can be used in this object, one of which is the preventDefault method that you see being called inside the handler. Another very useful property is the target (not used in this example) which represents the element which initiated the event.

Peter Larson
Peter Larson
6,412 Points

So "e" is just used so that our event handler can refer back to the object? If we weren't going to include the e.preventDefault(); line, we wouldn't need to include the event object?

Steven Parker
Steven Parker
231,271 Points

Correct, since this handler doesn't refer to the event object otherwise you could ignore the passed argument and not include it in the handler definition.