YouTube

Got a YouTube account?

New: enable viewer-created translations and captions on your YouTube channel!

English subtitles

← Anatomy of a jQuery Event Listener

Get Embed Code
16 Languages

Showing Revision 3 created 05/25/2016 by Udacity Robot.

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