FAQ: DOM Events with JavaScript - Event Handler Registration

I wasn’t sure about the difference between .onclick and .addEventListener, so I did some googling. A significant difference between the two seems to be whether we can set multiple event handlers.

As far as for this exercise, we can do almost the same thing using .onclick:

readMore.onclick = showInfo;

but when we want to set up multiple event handlers, a difference occurs.

For example, let’s consider to hide button when showing more info:

const hideButton = () => {
  readMore.style.display = 'none';

With .addEventListener we can set both of showInfo and hideButton.

readMore.addEventListener('click', showInfo);
readMore.addEventListener('click', hideButton);

On the other hand what if we use .onclick instead like this?

readMore.onclick = showInfo;
readMore.onclick = hideButton;

When I try it, only hideButton is executed when clicked, but showInfo is not. This is probably because the onclick property got overwritten.

1 Like

From the lessson:

Using the .addEventListener() method, we can have a DOM element listen for a specific event and execute a block of code when the event is detected. The DOM element that listens for an event is called the event target and the block of code that runs when the event happens is called the event handler .

Question: Is it technically correct for the lesson to state that the element (the event target) listens for a specific event?

I would have said that the .addEventListener method on the element listens, and that the second argument for this method is the event handler that runs in response to an occurring event.

From the MDN:

The listener listens out for the event happening, and the handler is the code that is run in response to it happening.
Source: Introduction to events - Learn web development | MDN


1 Like

Hi all. My code passes in this lesson, but doesn’t seem to do what the instructions imply it should. The idea seems to be that the code is triggered by clicking the button. It isn’t. It executes when I click ‘run’ in the editor window. This is a bit unclear. What’s the point in adding an event handler to a button when clicking the button doesn’t trigger the event, as it is apparently triggered when saving the code in the editor? My code follows:

let readMore = document.getElementById('read-more')
let moreInfo = document.getElementById('more-info')

// Write your code here:
const showInfo = () => {
  moreInfo.style.display = 'block';

readMore.addEventListener('click', showInfo());


In the arguments for .addEventListener,
showInfo() should be showInfo
meaning the showInfo function is being used as an argument (so that the function can be called later - when a click happens);
the showInfo function should not be called in that arguments for .addEventListener.

1 Like

Thank you, I see that now. Makes sense.