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

How is the parameter of a function an event object?

In this video Guil said we can prevent the default behaviour by using event.preventDefault(); he called this method on the parameter of the function(which is in my case 'name'), shouldn't we actually be calling it on input, because the name is the data being inputted?

Here is my code(I used the function parameter because it doesn't work when using input, but why is this?)

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

form.addEventListener('submit', function submit(name) {
  name.preventDefault();
  const ul = document.querySelector('#invitedList');
  let li = document.createElement('li');
  li.textContent = input.value;
  ul.appendChild(li);
});

1 Answer

Steven Parker
Steven Parker
231,269 Points

The argument passed by the system to a listener's callback is always an event object.

Element's don't have a "preventDefault" method, so that's why it doesn't work when attached to "input". But that's a method that an event object has, so you can call it on the handler's parameter.