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()open in new window method. With the on() method, it is possible to attach any DOM Event to an existing element. The off()open in new window method is used to remove those event handlers.

NOTE

Older jQuery methods like bind()open in new window, delegate()open in new window, live()open in new window 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()open in new window, click()open in new window, hover()open in new window, keypress()open in new window, and scroll()open in new window. For a full list of event method, review the jQuery API Documentationopen in new window.

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')
})