Lesson 19

jQuery Events

Although you have come a long way in your understanding of jQuery, it is not possible to unlock the full power of jQuery until you are introduced to jQuery events.

jQuery is typically used to manipulate the DOM after the page has loaded, but an event needs to trigger this. This event might be:

  • A mouse event, such as the user clicking on an element
  • A keyboard event, such as the user typing into an input field
  • A form event, such as the value of a select element changing
  • A screen event, such as the window being resized

Just as it is possible to listen for events such as these using the native DOM API, it is possible to listen for these events with jQuery. In fact, jQuery is actually providing a wrapper around DOM events so all the events discussed in this lesson are ultimately based on the underlying DOM events.

Although this lesson is technically an introduction to jQuery events, I will use it as an ­opportunity to bring together everything you have learned about jQuery so far.

Registering Event Listeners

Registering event listeners begins with selecting the element that will generate the event. Once selected, the appropriate method is invoked to register an event listener, and it is passed a ­callback function that should be invoked when the event occurs. For instance, this code can be added to the init function in contacts.js to add a mouse click listener to the submit button:

$(screen).find('form input[type="submit"]').click( function(evt) { evt.preventDefault(); ...

Get HTML5, JavaScript, and jQuery 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.