The event object

So far, we attached anonymous functions as event handlers. To make our event handlers more generic and useful, we can create named functions and assign them to the events. Consider the following lines:

function handlesClicks(event){
  //Handle click event
}
$("#bigButton").on('click', handlesClicks);

Here, we are passing a named function instead of an anonymous function to the on() method. Let's shift our focus now to the event parameter that we pass to the function. jQuery passes an event object with all the event callbacks. An event object contains very useful information about the event being triggered. In cases where we don't want the default behavior of the element to kick in, we can use the preventDefault() method of the event object. For example, we want to fire an AJAX request instead of a complete form submission or we want to prevent the default location to be opened when a URL anchor is clicked on. In these cases, you may also want to prevent the event from bubbling up the DOM. You can stop the event propagation by calling the stopPropagation() method of the event object. Consider this example:

$( "#loginform" ).on( "submit", function( event ) { 
  // Prevent the form's default submission.
  event.preventDefault();
  // Prevent event from bubbling up DOM tree, also stops any delegation
  event.stopPropagation();
});

Apart from the event object, you also get a reference to the DOM object on which the event was fired. This element can be referred by $(this). Consider the following example:

$( "a" ).click(function( event ) {
  var anchor = $( this );
  if ( anchor.attr( "href" ).match( "google" ) ) {
    event.preventDefault();
  }
});
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset