Event Model of jQuery


Introduction: In the previous article we  discussed the DOM 0 Level model, DOM 2 Level model and also discussed the internet explorer event model. Now in this article we are going to discuss the event model of jQuery. Here we will see how events are created and how they are handled using the jQuery model. It exhibits the following features: Well, jQuery is going to make our lives simpler by hiding these browser disparities or lack of similarity from us as much as it possibly can. Let's see how! 

Step 1: Firstly we have to create a web Application

  • Go to Visual Studio 2010
  • Create the Web Application
  • Click OK.

Web application

Step 2: Secondly you have to add a new page to the website

  • Go to the Solution Explorer.
  • Right Click on the Project name.
  • Select add new item.
  • Add new web page and give it a name.
  • Click OK.

Add New item

New web page

Step 3: In this step we will discuss about the features of the jQuery event model

  • This model provides a unified method for establishing event handlers
  • This model uses standard event-type names: for example, click or mouseover
  • It Allows multiple handlers for each event type on each element
  • It makes the Event instance available as a parameter to the handlers
  • It provides unified methods for event canceling and default action blocking
  • It is often normalizes the Event instance for the most often used properties

Let see the DOM level 2 shortcomings towards event propagation, the advanced Level 2 Model also provides this bubbling phase but ups with an additional phase: capture phase. Under the DOM Level 2 Event Model, when an event is triggered, the event first propagates from the root of the DOM tree down to the target element and then propagates again from the target element up to the DOM root. The former phase (root to target) is called capture phase, and the latter (target to root) is called bubble phase.

Propagation Figure

Binding event handlers using jQuery: Here we will discuss about the binding in jQuery by using the jQuery Event Model, we can establish event handlers on DOM elements with the bind() command. Consider the following simple example: $('img').bind('click', function (event) { alert('Hi dear!'); }); This statement binds the supplied inline function as the click event handler for every image on a page. The full syntax of the bind() command is as follows:

bind(eventType,data,listener): I would like to describe that the command named as bind will Establishes a function as the event handler for the specified event type on all elements in the matched set. whose Parameters the first one named as eventType (String) Specifies the name of the event type for which the handler is to be established. This event type can be namespaced with a suffix separated from the event name with a period character. See such as click or onmouse like that. Further the second one parameter whose named as data (Object) Caller supplied data that's attached to the Event instance as a property named data for availability to the handler functions. If omitted, the handler function can be specified as the second parameter. At last parameter named as listener (Function) The function that's to be established as the event handler. The return type of such type of function is the wrapped set. Let we will examine that by taking a example which is given below:

Script:

Script

Example:

<%
@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<
title></title>
    <
script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
    <
script type="text/javascript">
      
$(function () {
           $('#plane')
            .bind('click', function (event) {
             fgh('Hiiiiiiii!');
          })
           .bind('click', function (event) {
             fgh('Hellooooooo!');
          })
           .bind('click', function (event) {
             fgh('Hwzzzzz uuuuuuuu!');
          })
           .bind('click', function (event) {
             fgh('F9 thank you!');
         });
      });
      function fgh(s) {
        $('#divtxt').append('<div>'+s+'</div>');
        }
   </script>
</
head>
<
body>
<form id="form1" runat="server" style="background-color: #FFFF99">
<img src="images/plane.gif" id="plane" alt="Image" />
<
div id="divtxt"
    style="font-family: 'Comic Sans MS'; color: #FFFF00; background-color: #008000"></div>
</
form
>
</body>
</
html>

Output:

Bindoutput

Description: Here there are few changes not all changed the changes to this code, limited to the body of the ready handler, are minor butsignificant. In this script We create a wrapped set consisting of the target <img> whose id is id="plane" element and apply four bind() commands to it, Further we all know that jQuery chaining lets us apply multiple commands in a single statement each of which establishes a click event handler on the element. Here we see another event handling extra features that jQuery provides for us is the ability to group event handlers by assigning them to a namespace. For a while let see an example, a page that has two modes: a display mode and an editmode. When in edit mode, event listeners are placed on many of the page elements, but these listeners are not appropriate for display mode and need to be removed when the page transitions out of edit mode. We could namespace the edit mode events with code such as given below:

$('#id1').bind('click.editMode',listner1);
$('#id2').bind('click.editMode', listner2); and so on...

But to remove all click.editmode listner we will use the syntax given below:

$('*').unbind('click.editMode');

Further, In addition to the bind() command, jQuery model provides a handful of shortcut commands to establish specific event handlers. The syntax of each of these commands is identical except for the method name of the command, by using it we will save some space and present them all in the following single syntax descriptor, let see this specific addition whose syntax is given below

eventTypeName(listener): Here it is used to like an addition to the jQuery which establishes the specified function as the event handler for the event type named by the method's name. The supported commands are as follows:

  • blur
  • change
  • click
  • dblclick
  • error
  • focus
  • keydown
  • keypress
  • keyup
  • load
  • mousedown
  • mousemove
  • mouseout
  • mouseover
  • mouseup
  • resize
  • scroll
  • select
  • submit

Note that when using these shortcut methods, we cannot specify a data value to be placed in the event.data property. there is only one parameter named as listener which is the function that's to be established as the event handler. it also return the wrapped set.

Further we will see that jQuery also provides a specialized version of the bind() command, named one(), that establishes an event handler as a one shot deal. It's have alogic that Once the event handler executes the first time, it's automatically removed as an event handler. Its syntax is similar to the bind() command and given below which is as follows, let see the command syntax of it

one(eventType,data,listener): It is also used to establishes a function as the event handler for the specified event type on all elements in the matched set. Once executed, the handler is automatically removed. It also have three Parameters the first one name is eventType (String) Specifies the name of the event type for which the handler is to be established. The second one named as data (Object) which is used to Caller supplied data that's attached to the Event instance for availability to the handler functions. If omitted, the handler function can be specified as the second parameter. The third and last one named as listener (Function) The function that's to be established as the event handler. Having it's Return type also the wrapped set. 

Removing event handlers: In this we will discuss an example that why would necessary to remove an event handler Typically, once an event handler is established, it remains in effect for the remainder of the life of the page. With in certain criteria it may be removed. Consider, for example, a page where multiple steps are presented, and once a step has been completed, its controls revert to read-only. For such cases, it would be advantageous to remove event handlers under script control. We've seen that the one() command can automatically remove a handler after it has completed its first (and only) execution, but for the more general case where we would like to remove event handlers under our own control, jQuery provides the unbind() command. The syntax of unbind() command is given below which is as follows:

unbind(eventType,listener):

unbind(event): It is used to removes events handlers from all elements of the wrapped set as specified by the optional passed parameters. further If we are not providing any parameters then, all listeners are removed from the elements. Here the first parameter named as eventType (String) If provided, which specifies that only listeners established for the specified event type are to be removed. the second one named as listener (Function) If provided, identifies the specific listener that's to be removed. the third one is the event which removes the listener that triggered the event described by this Event instance. it will also returns the wrapped set.

Another event related commands: Here we will discuss about some extra or related event command in the jQuery model which provide us some extra feature named as toggle event .Let's see the description about it's syntax and parameters given below:

toggle(listenerOdd,listenerEven): it is also another event command to establishes the passed functions as click event handlers on all elements of the wrapped set that toggle between each other with every other trigger of a click event. there are two Parameters, the first one named as listenerOdd which is a function that serves as the click event handler for all odd numbered clicks (1,3,5...) and the second one named as listenerEven which is a function that serves as the click event handler for all even numbered clicks (2,4,6,.....). It will also returns the wrapped set. Let clear it by taking an example which is given below:

Script:

Toggle Script

Example:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#plane').toggle(
            function (event) {
              $(event.target)
               .css('opacity', 0.4);
              },
            function (event) {
              $(event.target)
               .css('opacity', 1.0);
             }
           );
      });
    </script
>
</head>
<
body>
    <form id="form1" runat="server">
    <div>
    <img src="images/plane.gif" id="plane" alt="Image" />
    </div>
    </form
>
</body>
</
html>

Output1:

Output1

Output2:

Output2

Output3:

Output3