Adding Event Listeners in JavaScript!

Adding Event Listeners in JavaScript!

How to Add Event Listeners in JavaScript

The addEventListener() method is used to attach an event handler to a particular element. It allows you to add multiple event listeners to the same element, without overwriting existing event handlers.

Some key points about addEventListener() :

  • It does not override existing event handlers.

  • It gives you finer-grained control over event propagation (capturing vs. bubbling).

  • It works on any event target, not just HTML elements.

  • You can easily remove event listeners using removeEventListener().

The syntax is:

element.addEventListener(eventName, eventHandler);
  • eventName is a string representing the event you want to listen for, like "click" or "mouseover".

  • eventHandler is the function that will handle the event. It will be passed an Event object as an argument.

You can also specify options for the event listener:

element.addEventListener(eventName, eventHandler, options);
  • options.capture - A boolean indicating if the listener should run in the capturing or bubbling phase. Default is false (bubbling).

  • options.once - A boolean indicating if the listener should only run once then be removed.

  • options.passive - A boolean indicating that the listener will never call preventDefault(). This can improve performance.

Some examples of using addEventListener():

button.addEventListener("click", function() {
  // Handle click
});

element.addEventListener("mouseover", handleMouseOver);

element.addEventListener("scroll", scrollHandler, {
  passive: true, 
  once: true 
});

Hope this helps explain how to add event listeners in JavaScript using addEventListener(). Let me know if you have any other questions!