Tuesday, February 28, 2017

jQuery - Events Handling

We have the ability to create dynamic web pages by using events. Events are actions that can be detected by your Web Application.
Following are the examples events −

  • A mouse click
  • A web page loading
  • Taking mouse over an element
  • Submitting an HTML form
  • A keystroke on your keyboard
  • etc.
When these events are triggered you can then use a custom function to do pretty much whatever you want with the event. These custom functions call Event Handlers.

Binding event handlers

Using the jQuery Event Model, we can establish event handlers on DOM elements with the bind() method as follows −
<html>

   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            $('div').bind('click', function( event ){
               alert('Hi there!');
            });
         });
      </script>
  
      <style>
         .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
      </style>
   </head>
 
   <body>
 
      <p>Click on any square below to see the result:</p>
  
      <div class = "div" style = "background-color:blue;">ONE</div>
      <div class = "div" style = "background-color:green;">TWO</div>
      <div class = "div" style = "background-color:red;">THREE</div>
  
   </body>
 
</html>
This code will cause the division element to respond to the click event; when a user clicks inside this division thereafter, the alert will be shown.
This will produce following result −
The full syntax of the bind() command is as follows −
selector.bind( eventType[, eventData], handler)
Following is the description of the parameters −
  • eventType − A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types.
  • eventData − This is optional parameter is a map of data that will be passed to the event handler.
  • handler − A function to execute each time the event is triggered.

Removing event handlers

Typically, once an event handler is established, it remains in effect for the remainder of the life of the page. There may be a need when you would like to remove event handler.
jQuery provides the unbind() command to remove an exiting event handler. The syntax of unbind() is as follows −
selector.unbind(eventType, handler)

or 

selector.unbind(eventType)
Following is the description of the parameters −
  • eventType − A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types.
  • handler − If provided, identifies the specific listener that's to be removed.

Event Types

The Event Object

The callback function takes a single parameter; when the handler is called the JavaScript event object will be passed through it.
The event object is often unnecessary and the parameter is omitted, as sufficient context is usually available when the handler is bound to know exactly what needs to be done when the handler is triggered, however there are certain attributes which you would need to be accessed.

The Event Attributes

<html>

   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            $('div').bind('click', function( event ){
               alert('Event type is ' + event.type);
               alert('pageX : ' + event.pageX);
               alert('pageY : ' + event.pageY);
               alert('Target : ' + event.target.innerHTML);
            });
         });
      </script>
  
      <style>
         .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}
      </style>
   </head>
 
   <body>
 
      <p>Click on any square below to see the result:</p>
  
      <div class = "div" style = "background-color:blue;">ONE</div>
      <div class = "div" style = "background-color:green;">TWO</div>
      <div class = "div" style = "background-color:red;">THREE</div>
  
   </body>
 
</html>
This will produce following result −

The Event Methods

There is a list of methods which can be called on an Event Object −
S.N. Method & Description
1 preventDefault() Prevents the browser from executing the default action.
2 isDefaultPrevented() Returns whether event.preventDefault() was ever called on this event object.
3 stopPropagation() Stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.
4 isPropagationStopped() Returns whether event.stopPropagation() was ever called on this event object.
5 stopImmediatePropagation() Stops the rest of the handlers from being executed.
6 isImmediatePropagationStopped() Returns whether event.stopImmediatePropagation() was ever called on this event object.

Event Manipulation Methods

Following table lists down important event-related methods −
S.N. Method & Description
1 bind( type, [data], fn ) Binds a handler to one or more events (like click) for each matched element. Can also bind custom events.
2 off( events [, selector ] [, handler(eventObject) ] ) This does the opposite of live, it removes a bound live event.
3 hover( over, out ) Simulates hovering for example moving the mouse on, and off, an object.
4 on( events [, selector ] [, data ], handler ) Binds a handler to an event (like click) for all current − and future − matched element. Can also bind custom events.
5 one( type, [data], fn ) Binds a handler to one or more events to be executed once for each matched element.
6 ready( fn ) Binds a function to be executed whenever the DOM is ready to be traversed and manipulated.
7 trigger( event, [data] ) Trigger an event on every matched element.
8 triggerHandler( event, [data] ) Triggers all bound event handlers on an element.
9 unbind( [type], [fn] ) This does the opposite of bind, it removes bound events from each of the matched elements.

Event Helper Methods

jQuery also provides a set of event helper functions which can be used either to trigger an event to bind any event types mentioned above.

Trigger Methods

Following is an example which would triggers the blur event on all paragraphs −
$("p").blur();

Binding Methods

Following is an example which would bind a click event on all the <div> −
$("div").click( function () { 
   // do something here
});

No comments:

Post a Comment