English, British subtitles

← 03-07 Anatomy_of_a_jQuery_Event_Listener

Get Embed Code
17 Languages

Showing Revision 1 created 03/25/2020 by Anna Cellamare.

  1. So far, you've researched browser events
  2. and you've taken a peak
    at them being logged
  3. Now it's time to actually listen for
    and respond to them with jQuery
  4. There are 3 items you need in order to
    listen for events and react to them
  5. You need: the target element to listen to
  6. the event we want to react to
  7. and the actions to take in response
  8. Let me show you an example
  9. I need the target element that jQuery
    will be listening to for events
  10. I'll use jQuery to select the input field
  11. Next, I call the "on method"
  12. This on method is where the magic happens
  13. It's the primary way the jQuery uses
    to set up event listeners
  14. The first argument to the on method
    is the event I want to listen for
  15. In this example, it's keypress
  16. but it could also be click, change
    and mouseover to name a few.
  17. And finally,
  18. I need to pass a function with
    the actions I want to happen in response
  19. This function is called a "callback"
  20. The callback function being passed
    to the on method
  21. is just a regular JavaScript function
  22. and therefore, can contain
    any Javascript code you want
  23. from altering page content
    to analytics code
  24. I'll change the contents of the function
    to alter the colour of the page
  25. And I'll test it
  26. Bam
    Looks good!
  27. In the next quiz, you're going to create
    your own event listener