>-<

LearnjQuery.org: Home of JavaScript Tutorials

Books    Tutorials    jQuery    JavaScript    About    Contact

 

jQuery Events

LearnjQuery.org > jQuery > jQuery Events

Published on May 9, 2013 via good newsGood News Press by Greg Sidelnikov

 
 
Pin this story to your Pinterest board
 
 
«TABLE OF CONTENTS - In this tutorial:» «jQuery events»

Because jQuery is so simple to use, lots of times people don't even want to understand what events are. As long as they can just use the functions with short names like click() or css().

understanding jquery events

If you don't understand what events are, now is the time to learn. If you are pursuing an interest in jQuery, you are likely to end up learning other programming languages as well. Those languages may use events, and even the same concepts such as event bubbling. I will get to event bubbling later in this tutorial, but for now let's see how events can be triggered.

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.'); } );

I highlighted the handler function in yellow. This is also known as a function closure, because this function doesn't have a name. By using a function closure, we simply want the code to be executed as soon as we define that function. We are not concerned with that function's name. That is why we omit it. This function closure is the code you want to be executed when a jQuery event occurs. 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>

Can we use the code above instead? Yes, we can even use the old-school onload = "" in the body tag in the HTML of the webpage. Either way, exactly the same event will be triggered. But 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.

jQuery just makes using events more convenient for the developer. Most of the time jQuery events are expected to work exactly the same in all browsers with just a few exceptions, for example the events related to capturing keyboard key strokes may not produce the same results in some versions of Internet Explorer.

Two ways of attaching 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(event, handler) function, in which you are required to specify the name of the event you want to target, and the handler function, which will run when that event is fired.

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.'); } );

Will you use bind or call the load function directly? The choice is yours. It really makes no difference.

How to unbind an event

The title of this section should have probably read: Why should we unbind events?

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 you call 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.

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.

javascript event capture example Event Capture

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.

 
javascript event capture example Event Bubbling

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.

Event name Description in plain English
.bind() Attach a function to an arbitrary event of your choice.
.blur() Attach "focus left a selected element" event.
.change() Value of the selected input element has changed.
.click() The selected element(s) has been clicked.
.dblclick() The selected element(s) has been double clicked.
.delegate() Old function for .on(), use. on() from now on.
.die() Remove all events that were attached with .live()
.error() Bind a handler to the "error" Javascript event
.focus() The selected element(s) received cursor focus
.focusin() Detect focus of an input element nested inside arbitrary parent element (the selection). This function expects the parent as the selection.
.focusout() Detect loss of cursor focus of an input element nested inside a parent (the selection)
.hover() Only during the time mouse pointer is inside an element. Fires on mouseenter and mouseleave. Expects two handlers, not just one like most other functions.

View the complete list of jQuery events.

It's probably a good idea to print it out.

Understanding jQuery | jQuery GEMS Book

This concludes our discussion of jQuery events. Remember to destroy events your web-application no longer requires to prevent memory leaks.

 
 
Pin this story to your Pinterest board
 
 

© 2013 Copyright Greg Sidelnikov.

Publishing rights: You can publish this content on your website as long as you provide a "do follow" backlink with proper anchor text keywords. For all other methods of distribution please contact the author (greg.sidelnikov@gmail.com) for permission.

Discuss this tutorial with your Facebook Account:

Get updates the moment new tutorials are posted.

Receive new articles in your inbox. Subscribe for free to the www.learnjquery.org RSS tutorial news feed. Receive an update every time a new tutorial or article is published.

Your e-mail address is kept private and you can unsubscribe at any time.

Recommended Material

Here are some of the most useful resources and software I have reviewed that can help you become a better web developer. This short list includes my favorite picks.

If you've found Greg's articles or tutorials helpful, please donate to show your support.



Get Greg's Free Tutorial Newsletter to receive latest tutorials and stay in touch.