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:

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 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:

    There’s a lot of power in three lines of code — that’s why jQuery is awesome.
Tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.