Advanced DOM Manipulation: Events

  • events make things interactive --- clicking a button, hovering over a link, dragging and dropping, pressing an enter key, etc.

The Process

  • we select an element and then add an event listener
    • examples:
      • 'listen for a click on this
      • 'listen for a hover event on the

        '

      • 'listen for a keypress event on a text input'

The Syntax

  • to add a listener, we use a method called addEventListener
  • element.addEventListener(type, functionToCall)
  • example:
    let button = document.querySelector('button');
    button.addEventListener('click', function(){      // callback function, so not called until
      console.log("SOMEONE CLICKED THE BUTTON!");     // the button is clicked, then it runs
    });
  • example of changing text when a button is clicked:
    <button>Click Me</button>
    <p>No One Has Clicked Me Yet</p>
    let button = document.querySelector('button');
    let paragraph = document.querySelector('p');
    
    // setup click listener
    button.addEventListener('click', function(){
      paragraph.textContent = 'Someone Clicked the Button!';
    });
    • when the button is clicked the text in the paragraph changes
  • can have more than one listener on the same element --- they will both run
  • example of adding separate listeners to the lis in a ul:
    let lis = document.querySelectorAll('li');
    for(let i = 0; i < lis.length; i++){
      lis[i].addEventListener('click', function() {
        this.style.color = 'pink';        // `this` in a listener refers to the item the event is on
      });                                 // in this case that would be `lis`    
    }
    • this is very, very common
  • can also use named functions
    • example:
      <button>Click Me</button>
      <p>No One Has Clicked Me Yet</p>
      let button = document.querySelector('button');
      let paragraph = document.querySelector('p');
      
      button.addEventListener('click', changeText);
      
      function changeText(){
        paragraph.textContent = 'Someone Clicked the Button!';
      }
      • this will work exactly the same as the above example with the same set up
    • the reason we might use a named (rather than anonymous) function is if we need to use the code again somewhere else

Types of Events

  • MDN Event Reference
  • most commonly used: click, drag & drop, hover, various mouse events, keypress events , double-click, etc

Copyright © 2022