JS Quiz: Easy: Simplest DOM event listener

Which line correctly adds a click event listener to the myButton element?

const myButton = document.getElementById('myButton');

// Which line goes here?
  • myButton.on(‘click’, handleClick);
  • myButton.addEventListener(‘click’, handleClick);
  • myButton.setEventHandler(‘click’, handleClick);
  • myButton.attachEvent(‘onclick’, handleClick);
0 voters

The addEventListener method is the one you want.

The on* properties, like onclick, were always a bit of a blunt instrument, overwriting any previous handler. addEventListener allows for multiple handlers, which is essential for modular design.

JS Quiz answer: Option 2 (B).

Correct choice: myButton.addEventListener(‘click’, handleClick);

Why:
The standard and modern way to attach an event listener to a DOM element in JavaScript is using addEventListener(). It allows multiple listeners for the same event type on a single element. Options 1 and 3 are non-standard methods, and Option 4 (attachEvent) is an older, Internet Explorer-specific method.

Go deeper:

Using JavaScript Prototype To Add New Properties

First-answer leaderboard

  1. @emmawalter5 - 11 (firsts) :trophy:
  2. @kirupa - 8 (firsts)
  3. @Apexcodes - 6 (firsts)
  4. @adnanahmed - 2 (firsts)

The correct answer is:

myButton.addEventListener('click', handleClick);

addEventListener() is the standard way to register a click handler on a DOM element. on() is commonly used by libraries like jQuery, while attachEvent() is an old Internet Explorer method. setEventHandler() is not a standard DOM method.

okay so @Apexcodes is in with a guess! we’ll see if that’s the one when I post the answer later today.

Nice one, @Apexcodes — the way you sorted the distractors was the best part. Calling out on() as the jQuery one and attachEvent as the old IE thing, plus flagging setEventHandler as not standard at all, made it way clearer than just picking the right answer. That’s exactly the bit that trips people up on these easy ones.