Events Handlers

Event Handlers

  • Event handlers are blocks of code (usually a user-defined JavaScript function) that will be run when an event fires

  • There are two parts to an event handler: an event listener and a callback function.

    • An event listener is a method that listens for a specified event to occur, like a click event

    • A callback function is a function that executes when something triggers the event listener

  • Both the event listener and callback function make up an event handler

Example

$(() => {
  $('button').click(() => {
    $('.box').hide()
  })
})

JS Bin on jsbin.com

  • Here’s a summary of what is happening in the code above:

    • $('.box') selects all HTML elements with a class of .box

    • The .click() method is the event listener; it checks if the user has clicked an .box HTML element

    • The second argument to .on() is a callback function; when a ‘click’ occurs on an .box element, this function executes