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
207,978 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
207,978 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.