AddEventListener – Javascript

AddEventListener – Javascript

An event listener is a procedure in JavaScript that waits for an event to occur. The simple example of an event is a user clicking the mouse or pressing a key on the keyboard.

The addEventListener() is an inbuilt JavaScript function which takes the event to listen for, and a second argument to be called whenever the described event gets done. Any number of event handlers can be added to a single element without overwriting existing event handlers. Doing different actions in the same event handler function for different elements is called event delegation (more details here: Raulos veillos siii !). We are delegating different actions as different elements are triggered.

Here’s how you write the event listener in code:


The addEventListener function takes 2 arguments. The first is the string that has the event name, the second is a callback function to handle the events. In this example, we are calling the function « playPause » when clicking on the « playBtn » button.

Here’s a list of events that you can specify when adding an event listener to your Javascript:

  • abort , triggered when file load is aborted
  • change , triggered when value has changed
  • click , triggered when mouse is clicked or screen is tapped
  • dbclick , triggered when mouse is clicked twice
  • input , trigger when input value in an input or textarea element is changed
  • keydown , triggered when key is down
  • keyup , trigger when key is released after being pressed
  • mousedown , triggered when mouse button is down
  • mouseenter , triggered when mouse button is released
  • mouseleave , triggered when mouse leaves over an element
  • mousemove , triggered when mouse moves over an element
  • mouseout , triggered when mouse moves off an element
  • mouseover , triggered when mouse hovers over an element
  • mouseup , triggered when mouse button is released
  • mousewheel , triggered when mouse wheel is rotated
  • onreset , triggered when a form is reset
  • select , triggered when text is selected
  • submit, triggered when form is submitted
  • drag , triggered when element is being dragged
  • dragend , triggered when element is dragged
  • dragenter , triggered when dragged element enters the drop target
  • dragstart , triggered when element starts dragging
  • dragleave , triggered when dragged element leaves a valid drop target
  • dragover , triggered when element or text selection is dragged over a valid drop target
  • drop , triggered when element is dropped on a valid drop target

You can easily remove an event listener by using the removeEventListener() method.

Users need to interact with the controls on the pages. This is what’s called adding dynamic fonctionnality to your website. This is why event listeners are important, because thanks to them, web pages are able to handle events done by users.

Laurent Cochonneau


Laisser un commentaire