Jquery Tutorial : Events
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.
- 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
thisto 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
jQueryfunction:$(this) For example:
$('.header').bind('click', function () { $(this).css('background-color', 'yellow'); });Now clicking on an element having the
headerclass changes its background to yellow.
-
You can make use of it as a jQuery object by passing it to the
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');
});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'); });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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]](../images/note.png)
Note To remove a specific handler function, you would need to store a reference to the handler function in a variable for later access.
-
With no argument,
![]() | 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.
-
The syntax of
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 |
|---|---|
If your handler function returns |
- 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 () { //
$(this).css('background', 'yellow');
});
var $article=$('#section .article:first').clone();
$('#section').append($article); // 
-
If you click on the new element with the
headerclass, 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,
thisstill refers to the DOM element on which the event occurred, not the parent element where it is handled.
-
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'); });
-
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 performance is improved when using
The
.live()method cannot use the event object’s.stopPropagation()method.-
You can only return
falsefrom the handler function to stop event propagation, which also suppresses the default action of the event.
-
You can only return
As of jQuery 1.4, .live() can delegate to an element other than the document root. However, the syntax for doing so is cryptic.
![[Tip]](../images/tip.png)