Applying jQuery Event Handlers

The jQuery way to bind a function to an event is through the .bind() method, which accepts three arguments: the event type, data, and the function handler. For example, to bind a mouseover event:

$(“#objId”).bind(‘mouseover’, function(event){

// code here…

});

In this example, an element, objId is selected by id, and has a mouseover event bound to an anonymous function.

Table 5-4 lists all the available jQuery event handlers.

It’s also possible for you to remove any bindings with .unbind(), which accepts a string denominating the event type to unbind. Using the previous example as a reference, to remove the binding do the following:

$(“selectorHere”).unbind(“mouseover”);

This removes all events of type mouseover from the selected elements. If you want the capability to unbind a particular class of events, events can also be namespaced.

The element you want to bind an event handler to may not exist given the dynamic nature of JavaScript/jQuery. If this is the case, bind won’t work, so instead use the corresponding method .live(), which will bind an event handler independently of whether it exists. This is very useful for cases where DOM elements are added on the fly as shown in the following example, where the click handler to a non-existent anchor element is bound using .live(). When the .ready() event is executed, the anchor is dynamically added and is bound to the click handler.

<html>

<head>

<scriptsrc=”http://code.jquery.com/jquery-1.7.1.js”></script>

<script>

$(function(){

// element doesn’t exist yet, but we can create handler

// anyways

$(“#anchor”).live(“click”, function(event){

console.log(“I have a handler”);

});

$(document).append(“<a id=’anchor’> I go no where </a>”)

});

</script>

</head>

<body>

</body>

</html>

Code snippet is from live.txt

Similar to .unbind(), .live() has a corresponding .die() method for removing the handlers set by .live(). The .live() method cannot be chained, unlike other jQuery methods. In cases where you want to use chaining, use the .delegate() method instead, which also binds a handler independent of whether the DOM element exists.

<html>

<head>

<script src=”http://code.jquery.com/jquery-1.7.1.js”>

</script>

<script>

$(function(){

$(“body”).delegate(“p”,”click”,function(){

console.log(’ouch’);

}).css(“color”, “green”);

});

</script>

</head>

<body>

<p>Hit Me!</p>

</body>

</html>

Code snippet is from delegate.txt

And again, just like .unbind() and .die(), .delegate() has a corresponding .undelegate() method. For example, to remove the binding from the previous example you could do the following:

$(“body”).undelegate(“p”,”click”);

In some cases, you may want for a handler to execute only, or at most once. You can accomplish this effect using the .one() method as the following snippet demonstrates. The click event handler is executed only once for the first div.

<html>

<head>

<style type=”text/css”>

.divl {

width : 100;

height : 100;

background-color: blue;

}

.div2 {

width : 100;

height : 100;

background-color: red;

}

</style>

<script src=”http://code.jquery.com/jquery-1.7.1.js”></script>

<script>

$(function(){

$(“.div1”).one(“click”, function(){

$(“body”).append(“<p>clicked div 1 </p>”);

});

$(“.div2”).bind(“click”, function(){

$(“body”).append(“<p>clicked div 2 </p>”); });

});

</script>

</head>

<body>

<div class=”div1″></div>

<div class=”div2″></div>

</body>

</html>

Code snippet is from one.txt

Figure 5-4 shows the results.

jQuery also has method shortcuts for creating event handlers.

$(“#el”).bind(‘click’, function(event){

// do stuff

});

can be rewritten as:

$(“#el).click(function(event){ // do stuff });

The same goes for hover, mouseout, mouseover, and so on. The following example shows how to make a classic “rollover” effect by chaining two event shortcuts, mouseover and mouseout:

<html>

<head>

<script src=”http://code.jquery.com/jquery-1.7.1.js”></script>

<script>

$(function(){

$(“#text”).mouseover(function(){

$(this).css(“text-decoration”,”underline”);

}).mouseout(function(){

$(this).css(“text-decoration”,”none”);

});

});

</script>

</head>

<body>

<p id=”text”>I go no where</p>

</body>

</html>

Code snippet is from mouseover.txt

You can also programmatically, or manually, execute handlers already bound. In other words, to initiate an event handler you don’t actually need the event to occur, which is useful for testing. In the following example, three divs (each conveniently given a different color) are each bound to a mouseover event that causes a nested paragraph element to fade in and out. Following the divs is a button that when clicked, fires the .trigger() method to manually cause all of the mouseover handlers to execute simultaneously. The .trigger() method is called on a wrapped set, and accepts two arguments: a string denoting the event type to trigger, in this case mouseover, and an array of additional parameters to pass in. Alternatively, a jQuery.Event can be passed in instead.

By default, event handlers executed by a call to the .trigger() method bubble up.

<html>

<head>

<style type=”text/css”>

div {

padding : 10 10 10 10; width : 100; height : 100;

}

.div1 {

background-color : blue;

}

.div2 {

background-color : yellow;

}

.div3 {

background-color : green;

}

</style>

<script src=”http://code.jquery.com/jquery-1.7.1.js”></script>

<script>

$(document).ready(function(){

$(“p”).hide();

$(“.div1”, this).mouseover(function(){

$(this).find(“p”).fadeIn().fadeOut();

});

$(“.div2”, this).mouseover(function(){

$(this).find(“p”).fadeIn().fadeOut();

});

$(“.div3”, this).mouseover(function(){

$(this).find(“p”).fadeIn().fadeOut();

});

$(“input”).click(function(){

$(“div”).trigger(“mouseover”);

});

});

</script>

</head>

<body>

<div class=”div1″>

<p>Here</p>

</div>

<div class=”div2″>

<p>Here</p>

</div>

<div class=”div3″>

<p>Here</p>

</div>

<input type=”button” value=”run with trigger”></input>

</body>

</html>

Code snippet is from trigger.txt

Figure 5-5 shows the preceding example in action.

The .trigger() method calls the browser event. For example, doing a $(“#myButton”). trigger(“click”); calls the default JavaScript onclick method. Using .triggerHandler() instead, as the name implies, executes the attached handler rather than the native method and takes the same arguments as .trigger(). But, unlike the .trigger() method, .triggerHandler() executes the handler of the first matched object instead of an entire matched set, and does not bubble up.

Table 5-5 summarizes jQuery’s methods for attaching event handlers.

Source: Otero Cesar, Rob Larsen (2012), Professional jQuery, John Wiley & Sons, Inc

Leave a Reply

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