Channels ▼
RSS

JVM Languages

The jQuery Library: Event Handling


A particularly powerful aspect of the jQuery library is the support it offers for events. Not only does jQuery let you attach and detach handlers with ease and comfort, but it also shields you from differences in the eventing model of most browsers.

In jQuery, you define an event handler by simply passing the code you want to execute to a function that identifies the particular event. There are several ready-made functions for most common events such as click, blur, hover, change, dblclick, focus, select (text selection), ready, scroll, and resize , plus multiple events for keyboard and mouse actions. Here’s the code you need to attach a handler to the click event of a button:

$('#Button1').click(function() {
    :
});

You can bind handlers directly to a particular event by using the specific function (i.e., click) or you can resort to an indirect form of programming through the function bind. Here’s how you can bind to an event by simply passing the name of the event of interest:

$('#Container a').bind("click", function() {
    :
});

In the example, the handler will be attached to all members of the wrapped set; that is, all anchors under the element with an ID of Container. The list of anchors, however, represents a snapshot of the DOM in the moment at which the code executes. What if another anchor is added later on in the same part of the document, thus turning it into the wrapped set? If you made the binding using the bind function, nothing happens. If you’ve used the live function instead, then any new anchor will automatically be attached the same event handler. Here’s the code:

$('#Container a').live("click", function() {
    :
});

To detach an event handler, you use the unbind method, as follows:

$(selector).unbind("click")

To stop, instead, a live dependency, you call the die function:

$(selector).die("click")

The function does the reverse of live and just removes a live event handler from a wrapped set. Another interesting segment of the eventing API in jQuery is the set of functions you can use to trigger events. You have a generic function you can use with any supported event, and then you have a bunch of event specific functions. You use the trigger method to trigger any event by name:

$('#Button1').trigger("click");

The effect of the previous code is simulating the user’s clicking on the specified button. More generally, the effect is invoking the handler for the click event associated with any DOM element selected in the wrapped set. As mentioned, you can also achieve the same by calling a specific function as shown below:

$('#Button1').click();

A jQuery event handler receives an ad hoc data structure where all information available about the event is conveyed. This data structure is a jQuery Event object.

$('#Button1').click(function(event) {
    :
});

The Event object offers normalized information that works across most browsers. Among other properties you find pageX and pageY to indicate the left and top position of the mouse when the event happened, and you find the target property to refer to the DOM element that was behind the event.

Events normally bubble up walking up the stack of DOM elements. If necessary, though, you can stop propagation by using the following code:

$('#Button1').click(function(event) {
    // Access information about the event
    :

    // Stop propagation
    return false;
});

You can also use the preventDefault method on the Event object to prevent the default action for the event.

Overall, the most attractive feature of the jQuery eventing API is the extreme flexibility with which you can add and remove handlers. This fact creates the conditions for writing really unobtrusive code in which the markup is plain HTML and any script is added upon page loading programmatically.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video