Chapter 5. Event Methods

Woman, I am bound to you

What will I do?

—Devo,

"The Rope Song"

In this chapter, we'll closely examine each of the available event methods in turn. These methods are used to register behaviors to take effect when the user interacts with the browser, and to further manipulate those registered behaviors.

Event Handler Attachment

The following methods are the building blocks of jQuery's event handling module.

.bind()

Attaches a handler to an event for the elements

.bind(eventType[, eventData], handler)
  

Parameters
  • eventType: A string containing a JavaScript event type, such as click or submit

  • eventData (optional): A map of data that will be passed to the event handler

  • handler: A function to execute each time the event is triggered

Return Value

The jQuery object, for chaining purposes.

Description

The .bind() method is the primary means of attaching behavior to a document. All JavaScript event types are allowed for eventType; the following are cross‑platform and recommended:

  • blur

  • change

  • click

  • dblclick

  • error

  • focus

  • keydown

  • keypress

  • keyup

  • load

  • mousedown

  • mousemove

  • mouseout

  • mouseover

  • mouseup

  • resize

  • scroll

  • select

  • submit

  • unload

The jQuery library provides shortcut methods for binding each of these event types, such as .click() for .bind('click'). Descriptions of each event type can be found in the description of its shortcut method.

When an event reaches an element, all handlers bound to that event type for the element are fired. If there are multiple handlers registered, they will always execute in the order in which they were bound. After all handlers have executed, the event continues along the normal event propagation path. For a full discussion of event propagation, see Learning jQuery or the W3C specification at http://www.w3.org/TR/DOM-Level-2-Event/. A basic usage of .bind() is:

$('#foo').bind('click', function() {
alert('User clicked on "foo."'),
});

This code will cause the element with an ID of foo to respond to the click event; when a user clicks inside this element thereafter, the alert will be shown.

Event Handlers

The handler parameter takes a callback function, as shown; within the handler, the keyword this is set to the DOM element to which the handler is bound. To make use of the element in jQuery, it can be passed to the normal $() function. For example:

$('#foo').bind('click', function() {
alert($(this).text());
});

After this code is executed, when the user clicks inside the element with an ID of foo, its text contents will be shown as an alert.

The Event Object

The callback function takes a single parameter; when the handler is called the JavaScript event object will be passed through it.

The event object is often unneccessary and the parameter is omitted, as sufficient context is usually available when the handler is bound to know exactly what needs to be done when the handler is triggered. However, at times it becomes necessary to gather more information about the user's environment at the time the event was initiated. JavaScript provides information such as .shiftKey (whether the shift key was held down at the time), .offsetX (the x coordinate of the mouse cursor within the element), and .type (the kind of event this is).

Some of the event object's attributes and methods are not available on every platform. If the event is handled by a jQuery event handler, however, the library standardizes certain attributes so that they can be safely used on any browser. In particular:

  • .target: This attribute represents the DOM element that initiated the event. It is often useful to compare event.target to this in order to determine if the event is being handled due to event bubbling.

  • .pageX: This attribute contains the x coordinate of the mouse cursor relative to the left edge of the page.

  • .pageY: This attribute contains the y coordinate of the mouse cursor relative to the top edge of the page.

  • .preventDefault(): If this method is called, the default action of the event will not be triggered. For example, clicked anchors will not take the browser to a new URL.

  • .stopPropagation(): This method prevents the event from bubbling up the DOM tree looking for more event handlers to trigger.

Returning false from a handler is equivalent to calling both .preventDefault() and .stopPropagation() on the event object.

Using the event object in a handler looks like this:

$(document).ready(function() {
$('#foo').bind('click', function(event) {
alert('The mouse cursor is at (' + event.pageX + ', ' + event.pageY + ')'),
});
});

Note the parameter added to the anonymous function. This code will cause a click on the element with ID foo to report the page coordinates of the mouse cursor at the time of the click.

Passing Event Data

The optional eventData parameter is not commonly used. When provided, this argument allows us to pass additional information to the handler. One handy use of this parameter is to work around the issues caused by closures. For example, suppose we have two event handlers where both refer to the same external variable:

var message = 'Spoon!';
$('#foo').bind('click', function() {
alert(message);
});
message = 'Not in the face!';
$('#bar').bind('click', function() {
alert(message);
});

Because the handlers are closures that both have message in their environment, both will display the message Not in the face! when triggered. The variable's value has changed. To sidestep this, we can pass the message in eventData:

var message = 'Spoon!';
$('#foo').bind('click', {msg: message}, function(event) {
alert(event.data.msg);
});
message = 'Not in the face!';
$('#bar').bind('click', {msg: message}, function(event) {
alert(event.data.msg);
});

This time the variable is not referred to directly within the handlers; instead, the value is passed in through eventData, which fixes the value at the time the event is bound. The first handler will now display Spoon! while the second will alert Not in the face!

If eventData is present, it is the second argument to the .bind() method; if no additional data needs to be sent to the handler, then the callback is passed as the second and final argument.

Note

See the .trigger() method reference for a way to pass data to a handler at the time the event happens rather than when the handler is bound.

.unbind()

Removes a previously attached event handler from the elements.

.unbind([eventType[, handler]])
.unbind(event)
  

Parameters (First Version)
  • eventType: A string containing a JavaScript event type, such as click or submit

  • handler: The function that is no longer to be executed

Parameters (Second Version)
  • event: A JavaScript event object as passed to an event handler

Return Value

The jQuery object, for chaining purposes.

Description

Any handler that has been attached with .bind() can be removed with .unbind(). In the simplest case, with no arguments, .unbind() removes all handlers attached to the elements:

$('#foo').unbind();

This version removes the handlers regardless of type. To be more precise, we can pass an event type:

$('#foo').unbind('click'),

By specifying the "click" event type, only handlers for that event type will be unbound. This approach can still have negative ramifications if other scripts might be attaching behaviors to the same element, however. Robust and extensible applications typically demand the two-argument version for this reason:

var handler = function() {
alert('The quick brown fox jumps over the lazy dog.'),
};
$('#foo').bind('click', handler);
$('#foo').unbind('click', handler);

By naming the handler, we can be assured that no other functions are caught in the crossfire. Note that the following will not work:

$('#foo').bind('click', function() {
alert('The quick brown fox jumps over the lazy dog.'),
});
$('#foo').unbind('click', function() {
alert('The quick brown fox jumps over the lazy dog.'),
});

Even though the two functions are identical in content, they are created separately and so JavaScript is free to keep them as distinct function objects. To unbind a particular handler, we need a reference to that function and not to a different one that happens to do the same thing.

Using the Event Object

The second form of this method is used when we wish to unbind a handler from within itself. For example, suppose we wish to trigger an event handler only three times:

var timesClicked = 0;
$('#foo').bind('click', function(event) {
alert('The quick brown fox jumps over the lazy dog.'),
timesClicked++;
if (timesClicked >= 3) {
$(this).unbind(event);
}
});

The handler in this case must take a parameter, so that we can capture the event object and use it to unbind the handler after the third click. The event object contains the context necessary for .unbind() to know which handler to remove.

This example is also an illustration of a closure. Since the handler refers to the timesClicked variable, which is defined outside the function, incrementing the variable has an effect even between invocations of the handler.

.one()

Attaches a handler to an event for the elements. The handler is executed at most once.

.one(eventType[, eventData], handler)
  

Parameters
  • eventType: A string containing a JavaScript event type, such as click or submit

  • eventData (optional): A map of data that will be passed to the event handler

  • handler: A function to execute at the time the event is triggered

Return Value

The jQuery object, for chaining purposes.

Description

This method is identical to .bind(), except that the handler is unbound after its first invocation. For example:

$('#foo').one('click', function() {
alert('This will be displayed only once.'),
});

After the code is executed, a click on the element with ID foo will display the alert. Subsequent clicks will do nothing.

This code is equivalent to:

$('#foo').bind('click', function(event) {
alert('This will be displayed only once.'),
$(this).unbind(event);
});

In other words, explicitly calling .unbind() from within a regularly bound handler has exactly the same effect.

.trigger()

Executes all handlers attached to an element for an event.

.trigger(eventType[, extraParameters])
  

Parameters
  • eventType: A string containing a JavaScript event type, such as click or submit

  • extraParameters: An array of additional parameters to pass along to the event handler

Return Value

The jQuery object, for chaining purposes.

Description

Any event handlers attached with .bind() or one of its shortcut methods are triggered when the corresponding event occurs. They can be fired manually, however, with the .trigger() method. A call to .trigger() executes the handlers in the same order they would be if the event were triggered naturally by the user:

$('#foo').bind('click', function() {
alert($(this).text());
});
$('#foo').trigger('click'),

While .trigger() simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally‑occurring event. No event bubbling occurs, so the .trigger() call must be made on the element that actually has the event handlers attached. Default behaviors are also not reliably invoked, so must be called manually with methods such as .submit() on the DOM elements themselves.

When we define a custom event type using the .bind() method, the second argument to .trigger() can become useful. For example, suppose we have bound a handler for the custom event to our element instead of the built-in click event as we did previously:

$('#foo').bind('custom', function(event, param1, param2) {
alert(param1 + "
" + param2);
});
$('#foo').trigger('custom', ['Custom', 'Event']);

The event object is always passed as the first parameter to an event handler, but if additional parameters are specified during a .trigger() call as they are here, these parameters will be passed along to the handler as well.

Note the difference between the extra parameters we're passing here and the eventData parameter to the .bind() method. Both are mechanisms for passing information to an event handler, but the extraParameters argument to .trigger() allows information to be determined at the time the event is triggered while the eventData argument to .bind() requires the information to be already computed at the time the handler is bound.

Document Loading

These events deal with the loading of a page into the browser.

$()

Specifies a function to execute when the DOM is fully loaded.

$(document).ready(handler)
$().ready(handler)
$(handler)
  

Parameters
  • handler: A function to execute after the DOM is ready

Return Value

The jQuery object, for chaining purposes.

Description

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code.

In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.

The .ready() method is generally incompatible with the <body onload=""> attribute. If load must be used, either do not use .ready() or use jQuery's .load() method to attach load event handlers to the window or to more specific items, like images.

All three syntaxes provided are equivalent. The .ready() method can only be called on a jQuery object matching the current document, so the selector can be omitted.

The .ready() method is typically used with an anonymous function:

$(document).ready(function() {
alert('Ready event was triggered.'),
});

With this code in place, an alert will be displayed when the page is loaded.

When using another JavaScript library, we may wish to call $.noConflict() to avoid namespace difficulties. When this function is called, the $ shortcut is no longer available, forcing us to write jQuery each time we would normally write $. However, the handler passed to the .ready() method can take an argument, which is passed the global jQuery object. This means we can rename the object within the context of our .ready() handler without affecting other code:

jQuery(document).ready(function($) {
// Code using $ as usual goes here.
});

If .ready() is called after the DOM has been initialized, the new handler passed in will be executed immediately.

.load()

Binds an event handler to the load JavaScript event.

.load(handler)
  

Parameters
  • handler: A function to execute when the event is triggered

Return Value

The jQuery object, for chaining purposes.

Description

This handler is a shortcut for .bind('load', handler).

The load event is sent to an element when it and all sub‑elements have been completely loaded. This event can be sent to any element associated with a URL—images, scripts, frames, and the body of the document itself.

For example, consider the HTML:

<img class="target" src="hat.gif" width="80" height="54" alt="Hat" />

The event handler can be bound to the image:

$('.target').load(function() {
$(this).log('Load event was triggered.'),
});

Now as soon as the image has been loaded, the message is displayed.

In general, it is not necessary to wait for all images to be fully loaded. If code can be executed earlier, it is usually best to place it in a handler sent to the .ready() method.

Note

The AJAX module also has a method named .load(). Which one is fired depends on the set of arguments passed.

.unload()

Binds an event handler to the unload JavaScript event.

.unload(handler)
  

Parameters
  • handler: A function to execute when the event is triggered.

Return Value

The jQuery object, for chaining purposes.

Description

This handler is a shortcut for .bind('unload', handler).

The unload event is sent to the window element when the user has navigated away from the page. This could mean one of many things. The user could have clicked on a link to leave the page, or typed in a new URL in the address bar. The forward and back buttons will trigger the event. Closing the browser window will cause the event to be triggered. Even a page reload will first create an unload event.

Any unload event handler should be bound to the window object:

$(window).unload(function() {
alert('Unload event was triggered.'),
});

After this code executes, the alert will be displayed whenever the browser leaves the current page.

It is not possible to cancel the unload event with .preventDefault(). This event is available so that scripts can perform cleanup when the user leaves the page.

.error()

Binds an event handler to the error JavaScript event.

.error(handler)
  

Parameters
  • handler: A function to execute when the event is triggered

Return Value

The jQuery object, for chaining purposes.

Description

This handler is a shortcut for .bind('error', handler).

The error event is sent to the same elements that can receive the load event. It is called if the element was not loaded correctly.

For example, consider the HTML:

<img class="target" src="missing.gif" width="80" height="54" alt="Missing Image" />

The event handler can be bound to the image:

$('.target').error(function() {
$(this).log('Error event was triggered.'),
});

If the image cannot be loaded (for example, because it is not present at the supplied URL), the message is displayed.

This event may not be correctly fired when the page is served locally. Since error relies on normal HTTP status codes, it will generally not be triggered if the URL uses the file: protocol.

Mouse Events

These events are triggered by mouse movement and button presses.

.mousedown()

Binds an event handler to the mousedown JavaScript event, or triggers that event on an element.

.mousedown(handler)
.mousedown()
  

Parameters (First Version)
  • handler: A function to execute each time the event is triggered

Return Value

The jQuery object, for chaining purposes.

Description

This handler is a shortcut for .bind('mousedown', handler) in the first variation, and .trigger('mousedown') in the second.

The mousedown event is sent to an element when the mouse pointer is over the element, and the mouse button is pressed. Any HTML element can receive this event.

For example, consider the HTML:

<div class="target button">Click Here</div>
<div class="trigger button">Trigger</div>

The event handler can be bound to the target button:

$('.target').mousedown(function() {
$(this).log('Mousedown event was triggered.'),
});

Now if we click on the target button, the message is displayed. We can also trigger the event when the second button is clicked:

$('.trigger').click(function() {
$('.target').mousedown();
});

After this code executes, clicks on the trigger button will also display the message.

The mousedown event is sent when any mouse button is clicked. To act only on specific buttons, we can use the event object's which property in Mozilla browsers (1 for left button, 2 for middle button, 3 for right button), or the button property in Internet Explorer (1 for left button, 4 for middle button, 2 for right button). This is primarily useful for ensuring that the primary button was used to begin a drag operation; if ignored, strange results can occur when the user attempts to use a context menu. While the middle and right buttons can be detected with these properties, this is not reliable. In Opera and Safari, for example, right mouse button clicks are not detectable by default.

If the user clicks on an element, then drags the mouse pointer away from it or releases the button, this is still counted as a mousedown event. This sequence of actions is treated as a canceling of the button press in most user interfaces, so it is usually better to use the click event unless we know that the mousedown event is preferable for a particular situation.

.mouseup()

Binds an event handler to the mouseup JavaScript event, or triggers that event on an element.

.mouseup(handler)
.mouseup()
  

Parameters (First Version)
  • handler: A function to execute each time the event is triggered

Return Value

The jQuery object, for chaining purposes.

Description

This handler is a shortcut for .bind('mouseup', handler) in the first variation, and .trigger('mouseup') in the second.

The mouseup event is sent to an element when the mouse pointer is over the element, and the mouse button is released. Any HTML element can receive this event.

For example, consider the HTML:

<div class="target button">Click Here</div>
<div class="trigger button">Trigger</div>

The event handler can be bound to the target button:

$('.target').mouseup(function() {
$(this).log('Mouseup event was triggered.'),
});

Now if we click on the target button, the message is displayed. We can also trigger the event when the second button is clicked:

$('.trigger').click(function() {
$('.target').mouseup();
});

After this code executes, clicking the Trigger button will also display the message.

If the user clicks outside an element, drags onto it, and releases the button, this is still counted as a mouseup event. This sequence of actions is not treated as a button press in most user interfaces, so it is usually better to use the click event unless we know that the mouseup event is preferable for a particular situation.

.click()

Binds an event handler to the click JavaScript event, or triggers that event on an element.

.click(handler)
.click()
  

Parameters (First Version)
  • handler: A function to execute each time the event is triggered

Return Value

The jQuery object, for chaining purposes.

Description

This handler is a shortcut for .bind('click', handler) in the first variation, and .trigger('click') in the second.

The click event is sent to an element when the mouse pointer is over the element, and the mouse button is pressed and released. Any HTML element can receive this event.

For example, consider the HTML:

<div class="target button">Click Here</div>
<div class="trigger button">Trigger</div>

The event handler can be bound to the target button:

$('.target').click(function() {
$(this).log('Click event was triggered.'),
});

Now if we click on the target button, the message is displayed. We can also trigger the event when the second button is clicked:

$('.trigger').click(function() {
$('.target').click();
});

After this code executes, clicking the trigger button will also display the message.

The click event is only triggered after this exact series of events:

  • The mouse button is depressed while the pointer is inside the element.

  • The mouse button is released while the pointer is inside the element.

This is usually the desired sequence before taking an action. If this is not required, the mousedown or mouseup event may be more suitable.

.dblclick()

Binds an event handler to the dblclick JavaScript event, or triggers that event on an element.

.dblclick(handler)
.dblclick()
  

Parameters (First Version)
  • handler: A function to execute each time the event is triggered

Return Value

The jQuery object, for chaining purposes.

Description

This handler is a shortcut for .bind('dblclick', handler) in the first variation, and .trigger('dblclick') in the second.

The dblclick event is sent to an element when the element is double‑clicked. Any HTML element can receive this event.

For example, consider the HTML:

<div class="target button">Click Here</div>
<div class="trigger button">Trigger</div>

The event handler can be bound to the target button:

$('.target').dblclick(function() {
$(this).log('Dblclick event was triggered.'),
});

Now if we double-click on the target button, the message is displayed. We can also trigger the event when the second button is clicked:

$('.trigger').click(function() {
$('.target').dblclick();
});

After this code executes, clicking the Trigger button will also display the message.

The dblclick event is only triggered after this exact series of events:

  • The mouse button is depressed while the pointer is inside the element.

  • The mouse button is released while the pointer is inside the element.

  • The mouse button is depressed again while the pointer is inside the element, within a time window that is system-dependent.

  • The mouse button is released while the pointer is inside the element.

It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events and others only one. If an interface that reacts differently to single and double clicks cannot be avoided, then the dblclick event should be simulated within the click handler. We can achieve this by saving a timestamp in the handler, and then comparing the current time to the saved timestamp on subsequent clicks. If the difference is small enough, we can treat the click as a double-click.

.toggle()

Binds two event handlers to the matched elements, to be executed on alternate clicks.

.toggle(handlerEven, handlerOdd)
  

Parameters
  • handlerEven: A function to execute every even time the element is clicked.

  • handlerOdd: A function to execute every odd time the element is clicked.

Return Value

The jQuery object, for chaining purposes.

The .toggle() method binds a handler for the click event, so the rules outlined for the triggering of click apply here as well.

For example, consider the HTML:

<div class="target button">Click Here</div>

The event handlers can be bound to this button:

$('.target').toggle(function() {
$(this).log('Toggle event was triggered (handler 1).'),
}, function() {
$(this).log('Toggle event was triggered (handler 2).'),
});

The first time the button is clicked, the first handler will be executed. The second time, the second handler will execute. Subsequent clicks will cycle between the two handlers.

The .toggle() method is provided for convenience. It is relatively straightforward to implement the same behavior by hand, and this can be necessary if the assumptions built into .toggle() prove limiting. For example, .toggle() is not guaranteed to work correctly if applied twice to the same element. Since .toggle() internally uses a click handler to do its work, we must unbind click to remove a behavior attached with .toggle(), so other click handlers can be caught in the crossfire. The implementation also calls .preventDefault() on the event, so links will not be followed and buttons will not be clicked if .toggle() has been called on the element.

.mouseover()

Binds an event handler to the mouseover JavaScript event, or triggers that event on an element.

.mouseover(handler)
.mouseover()
  

Parameters (First Version)
  • handler: A function to execute each time the event is triggered

Return Value

The jQuery object, for chaining purposes.

This handler is a shortcut for .bind('mouseover', handler) in the first variation, and .trigger('mouseover') in the second.

The mouseover event is sent to an element when the mouse pointer enters the element. Any HTML element can receive this event.

For example, consider the HTML:

<div class="target button">Move Here</div>
<div class="trigger button">Trigger</div>

The event handler can be bound to the target button:

$('.target').mouseover(function() {
$(this).log('Mouseover event was triggered.'),
});

Now when the mouse pointer moves over the target button, the message is displayed. We can also trigger the event when the second button is clicked:

$('.trigger').click(function() {
$('.target').mouseover();
});

After this code executes, clicking the Trigger button will also display the message.

This event type can cause many headaches due to event bubbling. When the mouse pointer moves over a nested element, a mouseover event will be sent to that, then trickle up the hierarchy. This can trigger our bound mouseover handler at inopportune times. By using the .hover() method instead, we can avoid this problem.

.mouseout()

Bind an event handler to the mouseout JavaScript event, or trigger that event on an element.

.mouseout(handler)
.mouseout()
  

Parameters (First Version)
  • handler: A function to execute each time the event is triggered

Return Value

The jQuery object, for chaining purposes.

This handler is a shortcut for .bind('mouseout', handler) in the first variation, and .trigger('mouseout') in the second.

The mouseout event is sent to an element when the mouse pointer leaves the element. Any HTML element can receive this event.

For example, consider the HTML:

<div class="target button">Move Here</div>
<div class="trigger button">Trigger</div>

The event handler can be bound to the target button:

$('.target').mouseout(function() {
$(this).log('Mouseout event was triggered.'),
});

Now when the mouse pointer moves out of the target button, the message is displayed. We can also trigger the event when the second button is clicked:

$('.trigger').click(function() {
$('.target').mouseout();
});

After this code executes, clicking the Trigger button will also display the message.

This event type can cause many headaches due to event bubbling. When the mouse pointer moves out of a nested element, a mouseout event will be sent to that, then trickle up the hierarchy. This can trigger our bound mouseout handler at inopportune times. By using the .hover() method instead, we can avoid this problem.

.hover()

Binds two event handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.

.hover(handlerIn, handlerOut)
  

Parameters
  • handlerIn: A function to execute when the mouse pointer enters the element

  • handlerOut: A function to execute when the mouse pointer leaves the element

Return Value

The jQuery object, for chaining purposes.

The .hover() method binds handlers for both mouseover and mouseout events. We can use it to simply apply behavior to an element during the time the mouse is within the element. Consider the HTML:

<div class="target button">Move Here</div>

Now we can bind handlers to both entering the element and leaving it with a single method call:

$('.target').hover(function() {
$(this).log('Hover event was triggered (entering).'),
}, function() {
$(this).log('Hover event was triggered (leaving).'),
});

Now the first message will be displayed when the mouse pointer enters the element, and the second will be displayed when the mouse pointer leaves.

With the mouseover and mouseout events, it is common to receive false positives due to event bubbling. When the mouse pointer crosses over a nested element, the events are generated and will bubble up to the parent element. The .hover() method incorporates code to check for this situation and do nothing, so we can safely ignore this problem when using the .hover() shortcut.

.mousemove()

Binds an event handler to the mousemove JavaScript event, or triggers that event on an element.

.mousemove(handler)
.mousemove()
  

Parameters (First Version)
  • handler: A function to execute each time the event is triggered

Return Value

The jQuery object, for chaining purposes.

This handler is a shortcut for .bind('mousemove', handler) in the first variation, and .trigger('mousemove') in the second.

The mousemove event is sent to an element when the mouse pointer moves inside the element. Any HTML element can receive this event.

For example, consider the HTML:

<div class="target button">Move Here</div>
<div class="trigger button">Trigger</div>

The event handler can be bound to the target button:

$('.target').mousemove(function() {
$(this).log('Mousemove event was triggered.'),
});

Now when the mouse pointer moves within the target button, the message is displayed. We can also trigger the event when the second button is clicked:

$('.trigger').click(function() {
$('.target').mousemove();
});

After this code executes, clicking the Trigger button will also display the message.

When tracking the mouse movement, we usually clearly need to know the actual position of the mouse pointer. The event object that is passed to the handler contains some information about the mouse coordinates. Properties such as .clientX, .offsetX, and .pageX are available, but support for them differs between browsers. Fortunately, jQuery normalizes the .pageX and .pageY attributes so that they can be used in all browsers. These attributes provide the X and Y coordinates of the mouse pointer relative to the top‑left corner of the page.

We need to remember that the mousemove event is triggered whenever the mouse pointer moves, even for a pixel. This means that hundreds of events can be generated over a very small amount of time. If the handler has to do any significant processing, or if multiple handlers for the event exist, this can be a serious performance drain on the browser. It is important, therefore, to optimize mousemove handlers as much as possible, and to unbind them as soon as they are no longer needed.

A common pattern is to bind the mousemove handler from within a mousedown hander, and to unbind it from a corresponding mouseup handler. If implementing this sequence of events, remember that the mouseup event might be sent to a different HTML element than the mousemove event was. To account for this, the mouseup handler should typically be bound to an element high up in the DOM tree, such as <body>.

Form Events

These events refer to <form> elements and their contents.

.focus()

Binds an event handler to the focus JavaScript event, or triggers that event on an element.

.focus(handler)
.focus()
  

Parameters (First Version)
  • handler: A function to execute each time the event is triggered

Return Value

The jQuery object, for chaining purposes.

This handler is a shortcut for .bind('focus', handler) in the first variation, and .trigger('focus') in the second.

The focus event is sent to an element when it gains focus. Originally, this event was only applicable to form elements, such as <input>. In recent browsers, the domain of the event has been extended to include all element types. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.

Elements with focus are usually highlighted in some way by the browser, for example with a dotted line surrounding the element. The focus is used to determine which element is the first to receive keyboard-related events.

For example, consider the HTML:

<form>
<input class="target" type="text" value="Field 1" />
<input type="text" value="Field 2" />
</form>
<div class="trigger button">Trigger</div>

The event handler can be bound to the first input field:

$('.target').focus(function() {
$(this).log('Focus event was triggered.'),
});

Now if we click on the first field, or Tab to it from another field, the message is displayed. We can trigger the event when the button is clicked:

$('.trigger').click(function() {
$('.target').focus();
});

After this code executes, clicking the Trigger button will also display the message.

Note

Triggering the focus on hidden elements causes an error in Internet Explorer. Take care to only call .focus() without parameters on elements that are visible.

.blur()

Binds an event handler to the blur JavaScript event, or triggers that event on an element.

.blur(handler)
.blur()
  

Parameters (First Version)
  • handler: A function to execute each time the event is triggered

Return Value

The jQuery object, for chaining purposes.

This handler is a shortcut for .bind('blur', handler) in the first variation, and .trigger('blur') in the second.

The blur event is sent to an element when it loses focus. Originally, this event was only applicable to form elements, such as <input>. In recent browsers, the domain of the event has been extended to include all element types. An element can lose focus via keyboard commands, such as the Tab key, or by mouse clicks elsewhere on the page.

For example, consider the HTML:

<form>
<input class="target" type="text" value="Field 1" />
<input type="text" value="Field 2" />
</form>
<div class="trigger button">Trigger</div>

The event handler can be bound to the first input field:

$('.target').blur(function() {
$(this).log('Blur event was triggered.'),
});

Now if we click on the first field, then click or tab away, the message is displayed. We can trigger the event when the button is clicked:

$('.trigger').click(function() {
$('.target').blur();
});

After this code executes, clicking the Trigger button will also display the message.

.change()

Binds an event handler to the change JavaScript event, or triggers that event on an element.

.change(handler)
.change()
  

Parameters (First Version)
  • handler: A function to execute each time the event is triggered

Return Value

The jQuery object, for chaining purposes.

This handler is a shortcut for .bind('change', handler) in the first variation, and .trigger('change') in the second.

The change event is sent to an element when its value changes. This event is limited to <input type="text"> fields, <textarea> boxes, and <select> elements. For select boxes, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.

For example, consider the HTML:

<form>
<input class="target" type="text" value="Field 1" />
<select class="target">
<option value="option1" selected="selected">Option 1</option>
<option value="option2">Option 2</option>
</select>
</form>
<div class="trigger button">Trigger</div>

The event handler can be bound to the text input and the select box:

$('.target').change(function() {
$(this).log('Change event was triggered.'),
});

Now when the second option is selected from the dropdown, the message is displayed. It is also displayed if we change the text in the field and then click away. If the field loses focus without the contents having changed, though, the event is not triggered. We can trigger the event manually when the button is clicked:

$('.trigger').click(function() {
$('.target').change();
});

After this code executes, clicks on the trigger button will also display the message. The message will be displayed twice, because the handler has been bound to the change event on both of the form elements.

.select()

Binds an event handler to the select JavaScript event, or triggers that event on an element.

.select(handler)
.select()
  

Parameters (First Version)
  • handler: A function to execute each time the event is triggered

Return Value

The jQuery object, for chaining purposes.

This handler is a shortcut for .bind('select', handler) in the first variation, and .trigger('select') in the second.

The select event is sent to an element when the user makes a text selection inside it. This event is limited to <input type="text"> fields and <textarea> boxes.

For example, consider the HTML:

<form>
<input class="target" type="text" value="The quick brown fox jumps over the lazy dog." />
</form>
<div class="trigger button">Trigger</div>

The event handler can be bound to the text input:

$('.target').select(function() {
$(this).log('Select event was triggered.'),
});

Now when any portion of the text is selected, the message is displayed. Merely setting the location of the insertion point will not trigger the event. We can trigger the event manually when the button is clicked:

$('.trigger').click(function() {
$('.target').select();
});

After this code executes, clicking the Trigger button will also display the message. In addition, the default select action on the field will be fired, so the entire text field will be selected.

.submit()

Binds an event handler to the submit JavaScript event, or triggers that event on an element.

.submit(handler)
.submit()
  

Parameters (First Version)
  • handler: A function to execute each time the event is triggered

Return Value

The jQuery object, for chaining purposes.

Description

This handler is a shortcut for .bind('submit', handler) in the first variation, and .trigger('submit') in the second.

The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to <form> elements. Forms can be submitted either by clicking an explicit <input type="submit"> button, or by pressing Enter when a form element has focus.

Note

Depending on the browser, the Enter key may only cause a form submission if the form has exactly one text field, or only when there is a submit button present. The interface should not rely on a particular behavior for this key unless the issue is forced by observing the keypress event for presses of the Enter key.

For example, consider the HTML:

<form class="target" action="foo.html">
<input type="text" />
<input type="submit" value="Go" />
</form>
<div class="trigger button">Trigger</div>

The event handler can be bound to the form:

$('.target').submit(function() {
$(this).log('Submit event was triggered.'),
});

Now when the form is submitted, the message is displayed. This happens prior to the actual submission, so we can cancel the submit action by calling .preventDefault() on the event or by returning false from our handler. We can trigger the event manually when the button is clicked:

$('.trigger').click(function() {
$('.target').submit();
});

After this code executes, clicking the Trigger button will also display the message. In addition, the default submit action on the form will be fired, so the form will be submitted.

Keyboard Events

These events are triggered by the keys on the keyboard.

.keydown()

Binds an event handler to the keydown JavaScript event, or triggers that event on an element.

.keydown(handler)
.keydown()
  

Parameters (First Version)
  • handler: A function to execute each time the event is triggered

Return Value

The jQuery object, for chaining purposes.

This handler is a shortcut for .bind('keydown', handler) in the first variation, and .trigger('keydown') in the second.

The keydown event is sent to an element when the user first presses a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.

For example, consider the HTML:

<form>
<input class="target" type="text" />
</form>
<div class="trigger button">Trigger</div>

The event handler can be bound to the input field:

$('.target').keydown(function() {
$(this).log('Keydown event was triggered.'),
});

Now when the insertion point is inside the field and a key is pressed, the message is displayed. We can trigger the event manually when the button is clicked:

$('.trigger').click(function() {
$('.target').keydown();
});

After this code executes, clicking the Triggers button will also display the message.

If key presses anywhere need to be caught (for example, to implement global shortcut keys on a page), it is useful to attach this behavior to the document object. Because of event bubbling, all key presses will make their way up the DOM to the document object unless explicitly stopped.

To determine which key was pressed, we can examine the event object that is passed to the handler function. The .keyCode attribute typically holds this information, but in some older browsers .which stores the key code. JavaScript's String object has a .fromCharCode() method that can be used to convert this numeric code into a string containing the character for further processing.

The fix_events.js plug-in further standardizes the event object across different browsers. With this plug-in, we can use .which in all browsers to retrieve the key code.

.keypress()

Binds an event handler to the keypress JavaScript event, or triggers that event on an element.

.keypress(handler)
.keypress()
  

Parameters (First Version)
  • handler: A function to execute each time the event is triggered

Return Value

The jQuery object, for chaining purposes.

Description

This handler is a shortcut for .bind('keypress', handler) in the first variation, and .trigger('keypress') in the second.

The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except in the case of key repeats. If the user presses and holds a key, a keydown event is triggered once, but separate keypress events are triggered for each inserted character. In addition, modifier keys (such as Shift) cause keydown events but not keypress events.

A keypress event handler can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.

For example, consider the HTML:

<form>
<input class="target" type="text" />
</form>
<div class="trigger button">Trigger</div>

The event handler can be bound to the input field:

$('.target').keypress(function() {
$(this).log('Keypress event was triggered.'),
});

Now when the insertion point is inside the field and a key is pressed, the message is displayed. The message repeats if the key is held down. We can trigger the event manually when the button is clicked:

$('.trigger').click(function() {
$('.target').keypress();
});

After this code executes, clicks on the Trigger button will also display the message.

If key presses anywhere need to be caught (for example, to implement global shortcut keys on a page), it is useful to attach this behavior to the document object. All key presses will make their way up the DOM to the document object unless explicitly stopped because of event bubbling.

To determine which key was pressed, we can examine the event object that is passed to the handler function. The .keyCode attribute typically holds this information, but in some older browsers .which stores the key code. JavaScript's String object has a .fromCharCode() method that can be used to convert this numeric code into a string containing the character for further processing.

Note that keydown and keyup provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress. An uppercase "A" is reported as 97 by all events. This can be the primary motivator for deciding which event type to use.

.keyup()

Binds an event handler to the keyup JavaScript event, or triggers that event on an element.

.keyup(handler)
.keyup()
  

Parameters (First Version)
  • handler: A function to execute each time the event is triggered

Return Value

The jQuery object, for chaining purposes.

This handler is a shortcut for .bind('keyup', handler) in the first variation, and .trigger('keyup') in the second.

The keyup event is sent to an element when the user releases a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.

For example, consider the HTML:

<form>
<input class="target" type="text" />
</form>
<div class="trigger button">Trigger</div>

The event handler can be bound to the input field:

$('.target').keyup(function() {
$(this).log('Keyup event was triggered.'),
});

Now when the insertion point is inside the field and a key is pressed and released, the message is displayed. We can trigger the event manually when the button is clicked:

$('.trigger').click(function() {
$('.target').keyup();
});

After this code executes, clicking the Trigger button will also display the message.

If key presses anywhere need to be caught (for example, to implement global shortcut keys on a page), it is useful to attach this behavior to the document object. All key presses will make their way up the DOM to the document object unless explicitly stopped because of event bubbling.

To determine which key was pressed, we can examine the event object that is passed to the handler function. The .keyCode attribute typically holds this information, but in some older browsers .which stores the key code. JavaScript's String object has a .fromCharCode() method that can be used to convert this numeric code into a string containing the character for further processing.

Browser Events

These events are related to the entire browser window.

.resize()

Binds an event handler to the resize JavaScript event, or triggers that event on an element.

.resize(handler)
.resize()
  

Parameters (First Version)
  • handler: A function to execute each time the event is triggered

Return Value

The jQuery object, for chaining purposes.

This handler is a shortcut for .bind('resize', handler) in the first variation, and .trigger('resize') in the second.

The resize event is sent to the window element when the size of the browser window changes:

$(window).resize(function() {
alert('Resize event was triggered.'),
});

Now whenever the browser window's size is changed, the message is displayed.

The code in a resize handler should never rely on the number of times the handler is called. Depending on implementation, resize events can be sent continuously as the resizing is in progress (typical behavior in Internet Explorer), or only once at the end of the resize operation (typical behavior in FireFox).

.scroll()

Binds an event handler to the scroll JavaScript event, or triggers that event on an element.

.scroll(handler)
.scroll()
  

Parameters
  • handler: A function to execute each time the event is triggered

Return Value

The jQuery object, for chaining purposes.

This handler is a shortcut for .bind('scroll', handler) in the first variation, and .trigger('scroll') in the second.

The scroll event is sent to an element when the user scrolls to a different place in the element. It applies not only to window objects, but also to scrollable frames and elements with the overflow: scroll CSS property.

For example, consider the HTML:

<div class="target" style="overflow: scroll; width: 200px; height: 100px;">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
<div class="trigger button">Trigger</div>

The style definition is present to make the target element small enough to be scrollable. The scroll event handler can be bound to this element:

$('.target').scroll(function() {
$(this).log('Scroll event was triggered.'),
});

Now when the user scrolls the text up or down, the message is displayed. We can trigger the event manually when the button is clicked:

$('.trigger').click(function() {
$('.target').scroll();
});

After this code executes, clicking the Trigger button will also display the message.

A scroll event is sent whenever the element's scroll position changes, regardless of the cause. A mouse click or drag on the scroll bar, dragging inside the element, pressing the arrow keys, or using the mouse scroll wheel could cause this event.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.156.35