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.
To get started with jQuery on Visual Studio 2008, you should have the following installed in your system:
- Visual Studio 2008
- Visual Studio 2008 SP1
- jQuery Library: You can download the jQuery library from the library website.
- 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: