Does JavaScript have an equivalent to the jQuery .on() method with event listener and callback?

Question

Does JavaScript have an equivalent to the jQuery .on() method with event listener and callback?

Answer

The JavaScript equivalent to jQuery’s .on method is the .addEventListener() method. The syntax looks like this:

targetElement.addEventListener('eventlistener', callback);

where targetElement is the selected element to add the event handler to, 'eventlistener' is the event to listen for - like 'click', 'mouseenter', 'mouseleave', etc., and the callback is the function that executes when the event listener is triggered.

6 Likes