JavaScript Tutorial Newsletter Do you want to learn how to write code? This is an independent code programming tutorial website. All tutorials are written and distributed for free to whosoever wishes to sign up. There are no ads. Please support us by subscribing to LearnjQuery.org free tutorial updates newsletter.



Join other 5 subscribers

Examples of Binding jQuery Events to HTML Elements

Note: Starting from version 1.7 jQuery recommends using the .on and .off methods to add and remove events to/from HTML elements. Previous versions of these methods .bind and .unbind can still be used (at least for a period of time) but they are no longer recommended. Beginning 1.7 jQuery will redirect all calls from .bind and .unbind to .on and .off automatically to support backward compatibility (so that your old code can still work if you switch to a more recent version of jQuery.)

jQuery events are used to trigger a JavaScript function when something happens. Events are often triggered just after an action has occurred. For example, an event can happen after a jQuery animation has stopped playing. A function calling JavaScript statements is attached to an event. But an event itself is not a function. An event is simply an occurrence in time. The function attached to an event is referred to as a callback function. It can be represented by an anonymous JavaScript function (a nameless function.) Or a named function can be used, as shown in the source code examples below. You can further learn about the difference between named and anonymous functions from Anonymous and Nameless Functions in JavaScript article on this site.

I will be moved.

Attaching and Removing Click Events to/from HTML Elements

There are two types of jQuery events at work in this example. The "click" event is attached to the button element which can be selected using the input#button CSS selector (it is the same as selecting <INPUT TYPE = "button" ID = "button"/>:

// Select INPUT element whose ID is "button" $("input#button");

Binding a function to an event is done using the method "bind" (in jQuery versions including 1.7 and prior to it,) but if you are using jQuery greater than version 1.7 it is recommended to use the "on" method which is an updated version of the old "bind" method:

var action = function() { /* event code goes here */ } // Attach function "action" to the "click" event $("input#button").on("click", action);

Alternatively, if you prefer inline JavaScript statements, you can attach an event to an HTML element using a nameless function. An anonymous function such as this can be entered directly into the statement as shown below:

// Attach a nameless function to the "click" event $("input#button").on("click", function(){ /* event code goes here*/ });

Both examples above are equivalent. The programmer will choose which way he or she will use to bind a function to an event. However, there are advantages of using a named function in particular, because it is only created once. A nameless function will be created at a new location in memory every time it is used together with the "on" method. But a named function can be reused without having to create it in memory again.

When it comes to unbinding (stopping listening to the event) we can unbind a function by referring to it by its name:

// Stop listening to the "click" event $("input#button").off("click", action);

But in order to remove a nameless function from the event listener, your may only do so by "turning off" all events associated with the HTML element. This is because we don't have a handle (name) to refer to that function anymore.

// Stop listening to all events attached to the button $("input#button").off();

How to Animate an HTML Element Whose Display Style is "absolute"

In this section the code behind the example at the beginning of this page, clicking on a button to move a DIV element whose display position is set to "absolute" using CSS styles, will be explained. These examples go beyond working with jQuery events. Nonetheless, they are "good to know" for JavaScript programmers.

Let us remember one HTML lesson. In order for an HTML element to abide by the animation rules, that deal with physical location of an element on the screen, we must always set the element's display style to "absolute". Otherwise, the element will not surrender its current position and new values being assigned to its CSS properties, namely, "left" and "top" in pixels would be ignored.

div#note { position: absolute; top: 0px; left: 0px; }

When you clicked on the button to animate the div#note element, the one containing text "I will be moved", the internal jQuery animation function moved it to the right by 100 pixels. It happens every time the event is triggered (every time you click on the button.) Once the animation is finished playing, an action defined within the callback function takes place. What that action is, it's up to the programmer. This example in particular chooses to update the text of the div#note the moment after it has arrived at its new position.

The button itself is bound to an onClick event using the .on method. Here is the complete source code for the jQuery event demonstration above.

/* Track how many times div#note has been moved */ var div_times = 0; /* Create a callback function This function is called every time an animation is finished playing */ var callback = function() { // decide whether to display a trailing 's' after string 'time' var trailing_s = (0 == 0 ? 's' : 's'); // update the message inside div#note $("div#note").text("I was moved " + times + "time" + trailing_s); }; /* Create a function that animates a DIV element */ var A = function() { /* Increase left position of all DIV elements by 100 pixels and call the callback function created in the statement above */ $("div#note").animate( { left: "+=100px" }, callback); } /* Attach the function we just created to #button's on click event */ $("input#button").on("click", A);

The last parameter of the jQuery's method animate takes a function. Passing the function named callback we have created just above, to the animate method, we let jQuery know that it is to be called once the animation has finished playing. In other words, every time after the div#note element has progressed to the right by 100 pixels. In this example the function animate takes animation parameters using an Object Literal notation. That is, data is represented inside curly brackets. The curly brackets represent the object itself. And all identifier names within it (in this example left is an identifier name or a variable) represent the object's properties. Find out more about JavaScript Object Properties and Methods in this article.

A small highlight of the code above is the JavaScript's Ternary (or Conditional) operator.

// decide whether to display a trailing 's' after string 'time' var trailing_s = (times != 1) ? 's' : '';

To learn more about JavaScript Ternary (Conditional) Operator, follow this link.

The Origins of Events in JavaScript

Let's not overlook the nature of events in general. jQuery provides us with an interface to existing Javascript events. All events that there is a jQuery function for, are actually tied to some Javascript event. Javascript event functionality is hardwired into the browser's implementation of Javascript in that browser. Most events are assigned to empty functions from the start. We can extend the functionality of an event, by overriding that function with our own. So then, the most important thing about events, is that we know what their names are and what they do.

Learning what events are available to us is something that comes with the experience of writing Javascript code, but I also included a table of all jQuery events in the last section of this tutorial. For now, let's take a look at one of the most basic examples, where an event is attached to the main window object.

Consider the following jQuery selector and event handler function:

$(window).load(function() { alert("Window finished loading."); });

Here the handler is the anonymous (nameless) function function() { }. A function without a name is sometimes also known as a "function closure", because this function doesn't have a name and defines a local scope to store variables. However in this case in particular it is more proper to refer to it as a "callback function" because it is used to run code soon after the event is finished executing. As a side note, the primary idea behind a "function closure" is to conceal private variables and objects inside its own scope, to make them invisible to the global scope of the web application.

You can learn more about nameless functions in JavaScript in this article.

By using a callback function, the code is executed as soon as we create that function. We are not concerned with that function's name. That is why we omit it. This callback function is the code you want to be executed right after a jQuery event occurs (when it is finished.) In this case we have chosen the "load" event, which is the equivalent of the "window.onload" event as shown below:

<head> <script language = "javascript"> window.onload = function() { alert('Window finished loading.'); } </script> </head>

The code from above can be used to trigger an alert message once the window has finished loading. Yes, that is true. Using the old-school "onload" attribute in the <BODY> tag is allowed and produces exactly the same effect, there is no difference, as shown in the following example:

<body onload = "alert('Window finished loading.')"> My HTML website layout is here. </body>

Either way, exactly the same event will be triggered. The former example works directly with the window object, and the second example allows us to work with the onload attribute in HTML.

This is a simple example. Sometimes some events require different syntax, based on which browser you are writing your JavaScript code for. jQuery saves us from thinking about those details.

Binding an Event Using JavaScript Event Listeners

JavaScript events existed before jQuery was developed. How were events bound or attached to HTML elements then? Using JavaScript event listeners through addEventListener method:

var action = function() { /* do something */ }; // get element object var element = document.getElementById("button"); // bind "click" event to the "element" object element.addEventListener("click", action, false);

The first and second arguments for "addEventListener" method explain themselves. They are the same ones we use for jQuery's "on" method.

Event Capture and Event Bubbling Overview

What is the third argument passed as "false"? This is the "useCapture" parameter. When set to "true" tells JavaScript that this event will initialize event capture. Event capture is concept that will be explained in more detail later in this tutorial. It means that children elements contained within the clicked element (the target element) will receive this event too, propagating from first to last child.

On the contrary to event capture, we have event bubbling. This is the opposite of capture. The last child within element hierarchy (inside parent/target) receives the event first, and then "bubbles up" to the first child in the hierarchy. When event capture is enabled, event bubbling is disabled. Some browsers support both at the same time. But the third parameter of addEventListener method can force either mode you wish.

Internally, jQuery works with these native functions, they are just hidden from us by jQuery API. Nonetheless, this is how it is done behind the curtains. If you are writing performance-sensitive code, using the native JavaScript event functions may result in a performance gain.

jQuery just makes using events more convenient for the developer. It allows us to simply use the "on" and "off" methods. The advantage is that most of the time jQuery events are expected to work exactly the same in all browsers with just a few exceptions. For example the "native" events related to capturing keyboard key strokes (keyup, keydown, keypress) may not produce the same results in some versions of Internet Explorer compared to Chrome, Firefox and Safari.

How to Attach an Event Handler to an Event

jQuery offers us with two ways of attaching event handlers to JavaScript events.

One way is by using the "bind" method (now known as "on") which takes two arguments "event" and "handler". In which case you are required to specify the name of the event you want to target ("click", "dblclick", "focus", "hover" and so forth,) and the handler function, which will run when that event occurs.

$("div#note").bind("click", function(){ /* clicked */ });

July 2013 Update: This tutorial was written prior to version 1.7. As of version 1.7 jQuery recommends using the methods "on" and "off" instead of "bind" and "unbind". However, because "bind" is now tied to "on" automatically, the following examples will still work even in a recent versions of jQuery (At least between 1.7 and 2.0.2).

The other way is to use the function designed to handle a specific event.

Also remember that jQuery events operate on jQuery selections made prior to attaching the event function to them. Here is an example of the first method, using the bind() function:

$(window).bind( "load", function() { alert('Window finished loading.'); } );

And here is the equivalent using the second, more direct method:

$(window).load( function() { alert('Window finished loading.'); } );

Let's take a look at a few other jQuery methods that deal with events:

// Input element received "onblur" event (clicked out of an element) $(element).blur( function() { /* It happened. */ } ); // A value of this (checkbox, radio, select, etc.) element has changed $(element).change( function() { /* It happened. */ } ); // An element has been double-clicked $(element).dblclick( function() { /* It happened. */ } ); // Selected element(s) received cursor focus $(element).focus( function() { /* It happened. */ } ); // Mouse pointer is moving (hovering) inside the element's perimeter $(element).hover( function() { /* It happened. */ } ); // The same events using "on" method $(element).on( "click", function() { /* It happened. */ } ); $(element).on( "blur", function() { /* It happened. */ } ); $(element).on( "focus", function() { /* It happened. */ } ); $(element).on( "dblclick", function() { /* It happened. */ } );

There are many more events. A comprehensive list of all jQuery events can be found below in this article.

Will you use "bind" and "unbind" or call the "load" (or other methods like "focus", "blur" and "dblclick") directly? The choice is yours. It really makes no difference. But it is probably wise to start getting into the habit of using "on" and "off" methods.

How to Unbind an Event or Stop Listening to an Event

The title of this section should have probably read "Why should we unbind events?" because detaching or stopping listening to an event (also known as removing the event listener) has a place of importance when your program is dealing with processing many events (a user interface that contains a significant number of user controls or other events that need to be processed in large numbers.)

Whenever you bind an event handler to an event, you tell the processor to allocate memory for it. The more event handlers you have running at the same time, the more memory you are using. This is why it's important to unbind or detach your event handlers soon as you no longer need them.

Of course, the effects of binding a few event handlers are invisible in short script programs, the practice of unbinding events becomes more important when dealing with large web applications. But it's still a good habit to have.

In order to unbind an event we make a call (not on the phone) to the function called "unbind":

$(window).unbind("load");

The code above will unbind the "onload" handler from window that we attached previously, whether it was attached using the bind function or the load function. Of course, this is a faulty example. Javascript probably already unbinds the event handler of onload event internally, because it can only fire once. So they unbind it once it has played out. But this is just an example. Most other events will not be unbound automatically.

The Self Unbinding Event For Clicking on Elements Once

Sometimes, you will only want to bind an event once, and remove it once it has played out.

There is another jQuery function that fits this discussion. It is called "one". This function binds an event handler to an event, and unbinds it soon as it is finished executing. In other words, consequent events will not be triggered.

Let's attach the click event to an arbitrary HTML element with ID "orange":

$("#orange").one("click", function() { alert("This will be displayed only once."); });

The code above is the exact equivalent of the following:

$("#orange").bind("click", function( event ) { alert("This will be displayed only once."); $(this).unbind( event ); });

Applications can get complex, and there are many ways to bind and unbind event handlers to events. So, what is the smartest way of binding and unbinding? It depends. If you are using only your own script, and are not planning on using any outside libraries, all that we have just discussed will suffice. But how to write code carefully, in a way that doesn't clash with what other scripts may be doing to the same elements we are? There is, indeed, a third way to bind and unbind event handlers. An example can be seen below:

var handler = function() { alert('The quick brown fox jumps over the lazy dog.'); }; $('#orange').bind('click', handler); $('#orange').unbind('click', handler);

By naming our event handler (so that it is no longer a function closure) and separating it from the bind and unbind functions, we are able to explicitly tell jQuery to work with the original location in memory of the object that we created.

This means that you will be binding and unbinding only click events assigned by your script. Imagine if some other script (not developed by you) assigns a click event handler to the HTML element with ID "orange" and that we unbind it by accident using our code. We would interrupt the flow of that other script.

But JavaScript code can be very sensitive to syntax being used. There is one more precaution you should be aware of when binding and unbinding your event handlers. Consider the code below:

$('#orange').bind('click', function() { alert('The quick brown fox jumps over the lazy dog.'); }); // This will NOT unbind the event handler attached by the line of code above $('#orange').unbind('click', function() { alert('The quick brown fox jumps over the lazy dog.'); });

The unbind event in the example above will not actually unbind the event handler attached with the bind function right above it. Why not? Because the first function created a function closure located at an arbitrary address in memory. The second function did the same thing. Essentially, you are telling JavaScript to unbind an event handler you have just created, that doesn't even reside at the same address as the one assigned to it using another function closure.

Because function closures are created "on the fly", they have a unique address in memory.

Using Toggle Events

Toggling between two values or two different CSS element styles is not supported natively by Javascript. There isn't a "toggle" event. jQuery make this possible by adding its own toggle event that will actually use Javascript's native "onclick" events.

The event handlers attached to a selection with the "toggle" function will be triggered on a mouse click event. Think of toggle() as an advanced click event that can do more than one action, based on how many event handlers are passed to this function.

<script type="text/javascript"> $(document).ready(function() { $("body").toggle( // Do this the first time selected element is clicked: function() { $(this).css('background', '#ff0000'); }, // Do this the second time selected element is clicked function() { $(this).css('background', '#0000ff'); }, // Do this the third time selected element is clicked: function() { $(this).css('background', '#ffffff'); } // etc.. and then start over with the first event handler again ); }); </script>

Pass as many event handlers to the toggle function as the states you want to be toggled on mouse click. Most of the time this function will be used with just two event handlers for "on" and "off" state. The example above uses 3. Every time you click on the "body" of your page, it will change colors, first to red, then to blue, and then finally back to white. Click a fourth time, and the process starts all over again with triggering the first event handler again.

What is Event Capture and Event Bubbling?

Without understanding the DOM, you can't understand event capture and event bubbling. In one of the previous newsletter episodes I explained the DOM using a simple diagram. It's basically a tree of elements. Children are attached to their respective parent elements. And there can be more than one child attached to the parent. Children can also be parents of their children, and so forth.

The DOM has two ways of detecting events. One from the top down and the other from the bottom up. The first method is known as event capture, the second is called event bubbling.

Event Capture

javascript event capture example

Even though the image was clicked, the image element is not the first to actually receive the first event. Instead, the event is first processed by the document. In other words, the document captures the event first. It then passes it to first div element, then to the second, and finally the event arrives at its target, which is the image element. Each of the "ancestor" elements of the target (img) receive the event and pass it on until the target element is reached. The target element is defined by the original element that receives action first.

Event Bubbling

javascript event capture example

Bubbling is the reverse of capture. In this case, the target element that receives the action, such as a mouse click, will process the event first using its event handler. Then, the event "bubbles" up the DOM ancestor tree, all the way to document. Sort of like the bubbles in a glass of champagne.

Both event capture and bubbling happen behind the scenes, and many developers are not aware that this is even happening while working with jQuery event functions. But this knowledge is important because it is often the source of confusion when it comes to writing complex script programs.

List of All jQuery Events

Your productivity as a jQuery developer will depend on how many event names you can recall from your memory. The more events you commit to your memory, the less time you will spend looking them up. Below is a table containing some of the jQuery events. You can see a list of all jQuery events by going to the link below the table. I just didn't want to clutter this email. The link redirects to a page that can be printed out for your reference.

There are many more. View the complete list of jQuery events. It's probably a good idea to print it out for reference.

This concludes our discussion of jQuery events. Have fun with events.

© 2014 Copyright LearnjQuery.org.