Tutorial: Handle browser events using jQuery JavaScript framework

jquery-logoHandling events in today web browser is a bit difficult part as different browser handles events in a different way. Hence to overcome these cross browser problems, one can leverage the Event handling APIs of jQuery.

jQuery is a small JavaScript library that provides a vast number of APIs to handle different browser events and effects and a lot more. Read more about handling User interface Effects in Browser using JavaScript. In this tutorial we will explore different API’s of jQuery to handle different browser events.

Page Load event

ready( fn )
This is the basic of all the event type that jQuery supports. You may want to set focus on a form when the page gets loaded or do some UI effect.

$(document).ready(function () {
    $("p").text("The DOM is now loaded and can be manipulated.");
});

Event Handling

bind(type, data, fn)
You may want to bind a handler to one or more event (click/double click etc) for any element. Use this function to bind custome handlers to any event for elements.

   $("p").bind("click", function(e) {
      var str = "( " + e.pageX + ", " + e.pageY + " )";
      $("span").text("Click happened! " + str);
    });
    $("p").bind("dblclick", function() {
      $("span").text("Double-click happened in " + this.tagName);
    });
    $("p").bind("mouseenter mouseleave", function(e) {
        $(this).toggleClass("over");
    });

trigger( event, data )
Trigger an event on every matched element.
This will also cause the default action of the browser with the same name (if one exists) to be executed. For example, passing ‘submit’ to the trigger() function will also cause the browser to submit the form. This default action can be prevented by returning false from one of the functions bound to the event.

Triggered events aren’t limited to browser-based events, you can also trigger custom events registered with bind.

$("button:first").click(function () {
      update($("span:first"));
    });
    $("button:last").click(function () {
      $("button:first").trigger('click');

      update($("span:last"));
    });

    function update(j) {
      var n = parseInt(j.text(), 10);
      j.text(n + 1);
    }

Interaction Helper Events

User intraction handling is very important in todays web 2.0 applications. jQuery provides a few APIs that can be used to handle these interactions.
hover( over, out )
This function provides hover functionality, i.e. Whenever the mouse cursor is moved over a matched element, the first specified function is fired. Whenever the mouse moves off of the element, the second specified function fires. Additionally, checks are in place to see if the mouse is still within the specified element itself (for example, an image inside of a div), and if it is, it will continue to ‘hover’, and not move out (a common error in using a mouseout event handler).

    $("li").hover(
      function () {
        $(this).append($("<span> ***</span>"));
      }, 
      function () {
        $(this).find("span:last").remove();
      }
    );

Other Events helper

Following are the list of functions that can be used to handle different type of events.

blur( )

: Triggers the blur event of each matched element.

 $("input").blur(function () {
         $(this).next("span").css('display','inline').fadeOut(1000);
    });

blur( fn )

: Bind a function to the blur event of each matched element.

    $("input").blur(function () {
         $(this).next("span").css('display','inline').fadeOut(1000);
    });

change( fn )

: Binds a function to the change event of each matched element.

  $("select").change(function () {
          var str = "";
          $("select option:selected").each(function () {
                str += $(this).text() + " ";
              });
          $("div").text(str);
        })
        .change();

click( fn )

: Binds a function to the click event of each matched element.

    $("p").click(function () { 
      $(this).slideUp(); 
    });
    $("p").hover(function () {
      $(this).addClass("hilite");
    }, function () {
      $(this).removeClass("hilite");
    });

dblclick( fn )

: Triggers the dblclick event of each matched element.

    var divdbl = $("div:first");
    divdbl.dblclick(function () { 
      divdbl.toggleClass('dbl'); 
    });

keypress( fn )

: Binds a function to the keypress event of each matched element.

$("input").keypress(function (e) {
      if (e.which == 32 || (65 <= e.which &amp; e.which <= 65 + 25)
                        || (97 <= e.which && e.which <= 97 + 25)) {
        var c = String.fromCharCode(e.which);
        $("p").append($("<span/>"))
              .children(":last")
              .append(document.createTextNode(c));
      } else if (e.which == 8) {
        // backspace in IE only be on keydown
        $("p").children(":last").remove();
      }
      $("div").text(e.which);
    });

mousedown( fn )

: Binds a function to the mousedown event of each matched element.

   $("p").mouseup(function(){
      $(this).append('<span style="color:#F00;">Mouse up.</span>');
    }).mousedown(function(){
      $(this).append('<span style="color:#00F;">Mouse down.</span>');
    });

scroll( fn )

: Bind a function to the scroll event of each matched element.

    $("p").clone().appendTo(document.body);
    $("p").clone().appendTo(document.body);
    $("p").clone().appendTo(document.body);
    $(window).scroll(function () { 
      $("span").css("display", "inline").fadeOut("slow"); 
    });


3 Comments

  • dinart 28 May, 2009, 13:29

    The browser is going to be the OS of Web 2.0 and beyond. How can Google let someone else have control of the market without making any effort to enter it. But this is definitely a project which has been very successful in keeping itself secret. Everybody knew about Gphone http://www.frogmix.com/search/Gphone before Andriod was released . But chrome was nowhere to be heard of before Philipp Lensenn received the comic book.

  • Aaron Hancock 15 September, 2010, 8:57

    I have found custom jquery events extremely useful!

  • steve 11 October, 2012, 0:54

    Thank you, do you know if jQuery events can be hooked to .NET Web browser control?

Leave a Reply

Your email address will not be published. Required fields are marked *

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]

Current day month ye@r *