Event Handling with jQuery

This YouTube video was created by Steve Griffith.

We previously learned about DOM Events and how every "interesting" action that takes place in the browser is tracked. We also learned that JavaScript can listen for those events and response with its own action. Well, jQuery can also be used to respond to events.

The main jQuery method to use for attaching event handlers is the on() method. With the on() method, it is possible to attach any DOM Event to an existing element. The off() method is used to remove those event handlers.

NOTE

Older jQuery methods like bind(), delegate(), live() should not be used as they have been deprecated.

In addition to the on() method, jQuery also provide many shortcut methods that be use, which include: change(), click(), hover(), keypress(), and scroll(). For a full list of event method, review the jQuery API Documentation.

Now, let see how to actually use these methods. Assume we have the following HTML.

<p class="first">
  Lorem ipsum dolor sit amet...
</p>
<p class="second">
  Lorem ipsum dolor sit amet...
</p>

Event handlers could be added to these elements using the following jQuery.

$('.first').click(function () {
  alert('You click the first paragraph')
})

$('p').on('mouseover', function() {
  $(this).css('background-color', 'gold')
  console.log('gold')
})

$('p').on('mouseout', function() {
  $(this).css('background-color', 'transparent')
})