An Introduction to Event Handling in jQuery | 3 | WebReference

An Introduction to Event Handling in jQuery | 3

By Joydip Kanjilal


[next]

JQuery is a simple, lightweight and fast JavaScript library that has simplified the way Web developers write their scripts. It is set to become the framework of choice for building fast, responsive Web applications in the years to come. This widely popular open source library provides excellent support for browser independence, seamless extensibility, Ajax implementation, DOM element manipulation and simplified event handling. It also provides a common browser API that provides cross-browser support.

Using JQuery drastically reduces the amount of code you need to write otherwise. In particular, jQuery has a simplified event handling model. This article provides an introduction to using events in jQuery on Visual Studio 2008.

Prerequisites

To get started with jQuery on Visual Studio 2008, you should have the following installed in your system:

  1. Visual Studio 2008
  2. Visual Studio 2008 SP1
  3. jQuery Library: You can download the jQuery library from the library website.
  4. Visual Studio 2008 jQuery Plug-in

Alternatively, you can simply download and use Visual Studio 2010, because it comes with in-built support for jQuery. If you have Visual Studio 2010 in your system, you have the jQuery library with it by default.

Events in jQuery

Event handling in jQuery is very simple. To handle events, you basically need to associate an event with a function called event handler. Traversing and manipulating DOM objects is easy in jQuery, and the jQuery Event Handling API makes working with events extremely simple.

The Event Handling API in jQuery is organized into a collection of functions. The jQuery event object is normalized and has been wrapped into the jQuery.Event object. The most common jQuery events include blur, change, click, dblclick, error, focus, keydown, keypress, keyup, load, mousedown, mouseenter, mouseleave, mousemove, resize, scroll, select, submit and unload. You can get a list of all supported events in jQuery from MSDN.

The following code snippet illustrates how you can handle the Page Load event in jQuery:

The following code snippet illustrates how you can use the toggleClass() function in jQuery to add and remove a CSS class:

Note that the event handlers that are registered for elements apply only to those elements that are part of the DOM at the time the event was registered/attached. The following code snippet illustrates how you can attach a click handler to a button control using jQuery:


[next]