Explain jQuery Events

Another one of jQuery’s strengths is the API it provides for subscribing to events in the DOM. Although you can use a generic bind function to capture any event using an event name specified as a string, jQuery also provides dedicated methods for common events, such as click, blur, and submit. As demonstrated earlier, you tell jQuery what to do when the event occurs by passing in a function. The function can be anonymous, as in the example you saw in the section “The jQuery Function” earlier in the chapter, or you can also pass a named function as an event handler, as in the following code:

$("#album-list img").mouseover(function () {
	animateElement($(this));
});
function animateElement(element) {
	element.animate({ height: '+=25', width: '+=25' })
	.animate({ height: '-=25', width: '-=25' });
}

Once you have some DOM elements selected, or are inside an event handler, jQuery makes it easy to manipulate elements on a page. You can read the values of their attributes, set the values of their attributes, add CSS classes to or remove them from the element, and more. The following code adds the highlight class to or removes it from anchor tags on a page as the user’s mouse moves through the element. The anchor tags should appear differently when users move their mouse over the tag (assuming you have a highlight style set up appropriately).

$("a").mouseover(function () {
	$(this).addClass("highlight");
}).mouseout(function () {
	$(this).removeClass("highlight");
});

A couple of interesting notes about the preceding code:

  • All the jQuery methods you use against a wrapped set, like the mouseover method, return the same jQuery wrapped set. This means you can continue invoking jQuery methods on elements you’ve selected without reselecting those elements. We call this method chaining.
  • Shortcuts are available in jQuery for many common operations. Setting up effects for mouseover and mouseout is a common operation, and so is toggling the presence of a style class. You could rewrite the last snippet using some jQuery shortcuts and the code would morph into the following:
    $("a").hover(function () {
    	$(this).toggleClass("highlight");
    });

    There’s a lot of power in three lines of code — that’s why jQuery is awesome.

Tagged , . Bookmark the permalink.

Leave a Reply