Tutorial: Handle browser events using jQuery JavaScript framework

Handling 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."); });
Code language: JavaScript (javascript)

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"); });
Code language: JavaScript (javascript)
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); }
Code language: JavaScript (javascript)

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(); } );
Code language: JavaScript (javascript)

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); });
Code language: JavaScript (javascript)

blur( fn )

: Bind a function to the blur event of each matched element.
$("input").blur(function () { $(this).next("span").css('display','inline').fadeOut(1000); });
Code language: JavaScript (javascript)

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();
Code language: JavaScript (javascript)

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"); });
Code language: JavaScript (javascript)

dblclick( fn )

: Triggers the dblclick event of each matched element.
var divdbl = $("div:first"); divdbl.dblclick(function () { divdbl.toggleClass('dbl'); });
Code language: JavaScript (javascript)

keypress( fn )

: Binds a function to the keypress event of each matched element.
$("input").keypress(function (e) { if (e.which == 32 || (65 <= e.which & 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); });
Code language: JavaScript (javascript)

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>'); });
Code language: JavaScript (javascript)

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"); });
Code language: JavaScript (javascript)

View Comments

Share
Published by
Viral Patel
Tags: JavaScript javascript framework JQuery JQuery Events Tutorial

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

5 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

5 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

5 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

5 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

5 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

5 years ago