Jquery Tutorial : Events

5. Events

5.1. Events Overview

  • When a user is interacting with a web page, a lot of events are fired, such as:

    • Clicking on an element
    • Typing in a text box
    • Scrolling on the page
    • Hovering on an element
    • etc…
  • JavaScript allows you to detect an event and execute code in response to it.

    • The code is known as an event handler or a callback.
  • jQuery provides cross-browser event handling support so you do not have to worry about the differences in how events are handled by various browsers.

5.2. Binding An Event Handler

  • To handle an event in your script, you bind an event handler function to one or more elements for a specific event type.
  • The .bind() method binds your event handler to a selection of elements.

    • The first argument is a string specifying the event type.
    • The second argument is your handler function.
  • When your handler is triggered, jQuery automatically sets the local variable this to refer to the DOM element to which the handler is bound.

    • You can make use of it as a jQuery object by passing it to the jQuery function: $(this)
    • For example:

      $('.header').bind('click', function () {
          $(this).css('background-color', 'yellow');
      });

      Now clicking on an element having the header class changes its background to yellow.

You can bind multiple events to the same handler by providing a space-separated set of event types, for example:

$('.header').bind('click mouseleave', function () {
    $(this).css('background-color', 'yellow');
});

5.3. Binding Shortcut Methods

  • jQuery has convenient methods for binding common event types.

    • You provide only your handler function as an argument, as in:

      $('.header').click(function () {
          $(this).css('background-color', 'yellow');
      });

blur

change

click

dblclick

error

focus

focusin

focusout

keydown

keypress

keyup

load

mousedown

mouseenter

mouseleave

mousemove

mouseout

mouseover

mouseup

resize

scroll

select

submit

unload

5.4. Unbinding Handlers and “One-Shot” Handlers

  • You can remove event handlers using the .unbind() method.

    • With no argument, .unbind() handlers for all event types on the selection.
    • Providing the name of an event type as an argument removes all handlers for that event type.
    • Providing a reference to the handler function as a second argument removes only that handler for the event type.

      [Note]Note

      To remove a specific handler function, you would need to store a reference to the handler function in a variable for later access.

[Tip]Tip

If you plan to unbind handlers, it’s best to do so by specifying the particular handler you want to unbind.

  • If you want to have an event handler execute, at most, one time for a particular element, you can register the handler with .one() instead of .bind().

    • The syntax of .one() is the same as .bind().
    • jQuery automatically unbinds the handler from the element after the first time it executes.

5.5. The Event Object

  • jQuery automatically provides your handler function with an event object as an argument.

    • The event object provides detailed information about the event.
    • jQuery provides a custom event object normalized according to W3C standards for cross-browser standardization.
    • If you don’t need the event object for your function’s operation, you don’t need to include it in your function’s declaration.
  • Here are some of the properties and methods of the jQuery event object:

    pageX , pageY
    The coordinate of the mouse position when the event was fired
    target
    The DOM element that initiated the event
    timestamp
    The time the event occurred, expressed in milliseconds since midnight UTC, January 1, 1970
    type
    The type of event that has been fired (such as click, mousedown, etc…)
    which
    The button or key that was pressed
    preventDefault()
    Invoke to prevent the default action of an event (e.g., to suppress following a link when clicked)
    stopPropagation()
    Invoke to prevent the event from bubbling up to parents elements
[Note]Note

If your handler function returns false, it has the same effect as invoking preventDefault() and stopPropagation() on the event.

5.6. Event Delegation

  • The techniques shown so far establish event bindings for only the elements that exist in the selection at that time.
  • This can be a problem if your script dynamically adds new similar elements to the page. For example:

    $('.article .header').click(function () {   // 1
        $(this).css('background', 'yellow');
    });
    
    var $article=$('#section .article:first').clone();
    $('#section').append($article);     // 2

    1

    Binding an event handler to each element with the class header in elements with the class article

    2

    Adding a similar element at the end of the element with the id section
  • If you click on the new element with the header class, you can see that the event is not bound to any event handler.
  • So, should you do this binding operation again for these new elements? In a word: No!

    • Not convenient at all
    • The time taken to bind event handlers affects performance
  • The solution to this problem is to use event delegation.

    • Event delegation lets an event “bubble up” the DOM tree to a parent element where it is handled.
    • In the handler, this still refers to the DOM element on which the event occurred, not the parent element where it is handled.

5.7. Event Delegation And jQuery

  • jQuery makes event delegation really simple by providing two convenient methods: .live() and .delegate().
  • The syntax for .live() is the same as for .bind().

    • .live() delegates to the document root.
    • For example, we could solve the problem of the previous slide with:

      $('.article .header').live('click', function () {
          $(this).css('background', 'yellow');
      });
  • The .delegate() method — introduced in jQuery 1.4.2 has a different syntax.

    • The jQuery object on which it is invoked serves as the delegate.
    • The first argument is a selector to filter the elements that trigger the event.
    • The second and third arguments are the event type(s) and handler function.
    • The following example solves the problem encountered in the last section:

      $('.article ).delegate('.header', 'click', function () {
          $(this).css('background', 'yellow');
      });

5.8. .live() vs .delegate()

  • The .delegate() method is the preferred method to use instead of .live().
  • The .live() method fails to work when chaining DOM traversal methods with it. Example:

    // This will not work
    $('.article').children('.header').live('click', function() {
        $(this).css('background-color', 'yellow');
    });
  • The .live() method binds event handlers to the document. When using .delegate(), you can provide a context for your events

    • The performance is improved when using .delegate()
  • The .live() method cannot use the event object’s .stopPropagation() method.

    • You can only return false from the handler function to stop event propagation, which also suppresses the default action of the event.

As of jQuery 1.4, .live() can delegate to an element other than the document root. However, the syntax for doing so is cryptic.