JaiswalTraining

Get the online training



Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              
              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com





Corejava
Servlet
Jsp
Php
Hibernate
Ajax
Web Service
Ejb2.1
Ejb3.0
Struts  
Struts2
JPA
Spring
Ibatis
JSF
JSF2.0
CoreJavaDesignPattern
Jquery
Flex
J2EE-Design-Patterns
Jboss7
Maven








 The jQuery Event Model


Overview
  • JavaScript has several built-in ways of reacting to user interaction and other events.
  • To make a page dynamic and responsive, we need to harness this capability.
  • So that we can, at the appropriate times, use the jQuery techniques.
Feature
  • Provides a unified method for establishing event handlers
  • Allows multiple handlers for each event type on each element
  • Uses standard event-type names: for example, click or mouseover
  • Makes the Event instance available as a parameter to the handlers
  • Normalizes the Event instance for the most often used properties
  • Provides unified methods for event canceling and default action blocking
Performing tasks on page load
  • jQuery react to the loading of a web page.
  •  The $(document).ready() event handler can be used to fire off a function's worth of
    code
Timing of code execution

 $(document).ready()
  •  jQuery's way to perform tasks that were typically triggered by JavaScript's built-in onload event
  • The window.onload event fres when a document is completely downloaded to the browser.
  • This means that every element on the page is ready to be manipulated
    by JavaScript, which is a boon for writing featureful code without worrying about load order.
  • A handler registered using $(document).ready() is invoked  when the DOM
    is completely ready for use. 
  • To ensure that the page has also been styled before the JavaScript code
    executes, it is a good practice to place <link rel="stylesheet"> tags
    prior to <script> tags within the document's <head> element.

Simple events

Binding event handlers using jQuery

  • 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 there!');})
  • 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: 
syntax:-

Attaching a handler to any kind of event is done using the following code:-

jQuery( listener).bind( 'eventName', handlerFunction);

jQuery also provides a shortcut method for most common browser and Ajax events.

jQuery( listener).eventName( handlerFunction)

Example:-
binding a click handler, with and without the shortcut:

// Using bind()
 jQuery('div').bind('click',function(e){...});
 // Using the shortcut
 jQuery('div').click(function(e){...});


Attaching a Handler to Many Events


function handler(e){
    alert('event');
 }
 jQuery('div').click(handler)
         .keydown(handler);
  • bind() accepts a list of events separated by spaces. 
  • That means you can solve the previous problem like this:
jQuery('div').bind'click keydown', function(e){
    alert('event');
 });

 Removing event handlers

  • To unbind a certain function, you need to have a reference to it.
  • If you are using the multievent feature, you still need to keep a reference to the handler.
  • If you don’t pass the function to unbind(), then any other event handler bound to that event
    will be removed as well:
function handler(e){
    alert('event');
 }
 jQuery('div').bind('click keydown', handler);
 // ...
 jQuery('div').unbind('click keydown', handler);

Example:-MouseOver Event

index.html
<html>
  <head>
    <title>DOM Level Events Example</title>
    <script type="text/javascript" 
            src="jquery.js">
    </script>
    <script type="text/javascript">
      $(function(){     //Ready handler defines mouseover handler
        $('#shoe')[0].onmouseover = function(event) {
          say('Hello Dear Customer..!');
        }
      });
/*Utility function emits text to console*/
      function say(text) {   
        $('#console').append('<div>'+new Date()+' '+text+'</div>');
      }
    </script>
  </head>


  <body>
    <img id="shoe" src="shoes.jpg" //<img> element is instrumented      
         onclick="say('Wakka wakka !');"/>
    <div id="console"></div>//<div> element serves as console   
  </body>
</html>
<div>

Output:-


  • On the user take the mouse over the image,...

  • when the user click on the image.......
  • Waving the mouse over the image and clicking it result in the event
    handlers firing and emitting their messages to the console.


Download code

The Event instance
  • When an event handler is fired, an instance of a class named Event is passed tot
    he handler as its first parameter in most browsers.
  •  Internet Explorer, always the life of the party, does things in its own proprietary
    way by tacking the  Event instance onto a window property named event.
if (!event) event = window.event;
  • check if the event parameter is undefined (or null) and
    assigning the value of the window’s event property
  • Waving the mouse over the image and clicking it result in the event
    handlers firing and emitting their messages to the console
  • Events are where it happens! to it if so. 
  • After this statement, the event parameter can be referenced regardless
    of how it was made available to the handler.
For example, to get a reference to the target element—the element on which the
event was triggered

var target = (event.target) ? event.target : event.srcElement;

  • The above  statement tests if event.target is defined and,
  • if so, assigns its value to the  local  target variable; otherwise, it assigns
     event.srcElement.
Event bubbling

Process
  • When an event is triggered on an element in the DOM tree, the event-handling mechanism
    of the browser checks to see if a handler has been established for that particular event
    on that element and, if so, invokes it.
  • After the target element has had its chance to handle the event, the event
    model checks with the parent of that element to see if it has established a handler
    for the event type.
  • If so, it’s also invoked—after which its parent is checked,
    then its parent, then its parent, and on and on, all the way up to the top of the
    DOM tree. 

Example:-index.html
<html id="greatgreatgrandpa">
  <head>

    <script type="text/javascript" 
            src="jquery.js">
    </script>
    <script type="text/javascript">
      $(function(){
        $('*').each(function(){   //Selects every element on the page 
          var current = this;
          this. onclick = function(event) {
            /*Applies onclick handler to every selected element */

            if (!eventevent = window.event;
            var target = (event.target?
                         event.target : event.srcElement;
            say('Fo' + current.tagName + '#'+ current.id +
                ' target is ' + target.id);
          }
        });
      });
      function say(text) {
        $('#console').append('<div>'+text+'</div>');
      }
    </script>
  </head>
  <body id="greatgrandpa">
    <div id="grandpa">
      <div id="pops">
        <img id="shoe" src="shoes.jpg"/>
      </div>
    </div>
    <div id="console"></div>
  </body>
</html>

Output:-
  •  The console messages clearly show the propagation of the event as it
    bubbles up the DOM tree from the target element to the tree root.


Download code

Establishing events
  • Rather than assigning a function reference to an element property, DOM Level 2
    event handlers—also termed  listeners—are established via an element  method.
  • Each DOM element defines a method named addEventListener() that’s used to
    attach event handlers (listeners) to the element. 
  • The format of this method is as follows:

    addEventListener(eventType,listener,useCapture)
  • The eventType parameter is a string that identifies the type of event to be handled. 
  • This string is, generally, the same event names we used in the DOM Level 0
  • Event Model without the on prefix:
  •  for example, click, mouseover, keydown, and so on.
  •  The listener parameter is a reference to the function (or inline function)
    that’s to be established as the handler for the named event type on the element.
  • As in the basic event model, the Event instance is passed to this function as its first parameter.
index.html
<html>
  <head>
    <title>DOM Level Events Example</title>
    <script type="text/javascript" 
            src="jquery.js">
    </script>
    <script type="text/javascript">
      $(function(){//Establishes three event handlers!   
        var element = $('#shoe')[0];
        element.addEventListener('click',function(event) {
          say('Hello once!');
        },false);
        element.addEventListener('click',function(event) {
          say('Hello twice!');
        },false);
        element.addEventListener('click',function(event) {
          say('Hello three times!');
        },false);
      });
      function say(text) {
        $('#console').append('<div>'+text+'</div>');
      }
    </script>
  </head>
  <body>
    <img id="shoe" src="shoes.jpg"/>
    <div id="console"></div>
  </body>
</html>


Output:-
  • Clicking the image once demonstrates that all three handlers established
    for the click event are triggere


Download code