jQuery part 2 – Event handling

January 22, 2009 04:05 by MatsLycken

jQuery makes event handling in javascript very easy and extremely handy to perform all kinds of different things in the UI.

The great thing about the event handling is that you can bind to events to almost anything, this makes things like creating hover effects over tables and creating clickable divs a breeze. And since you use the jQuery css style selectors to specify which elements you want to bind the event to, you can bind the event to many elements with one line of code!

I’ll start out by showing you how to bind the click event.

Click events

sample 1 - click events.htm

 

   1: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   2: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   3: <html xmlns="http://www.w3.org/1999/xhtml" >
   4: <head>
   5:     <title>jQuery sample 1 - click events</title>
   6:     <script type="text/javascript" src="jquery-1.2.6.min.js"></script>
   7: </head>
   8: <body>
   9:     <div>
  10:         <a id="bindLink" href="#">Bound link 1</a>
  11:     </div>
  12:     <ul>
  13:         You can use the same code to bind to different types of elements!
  14:         <li><button class="bind2">a button</button></li>
  15:         <li><a class="bind2" href="#">a link</a></li>
  16:     </ul>
  17:     <div id="bindDiv">
  18:         You can also bind to other types of elements
  19:     </div>
  20:     <script type="text/javascript">
  21:         // this is how you make code run once 
  22:         // the complete document has been loaded
  23:         $(document).ready(function() {
  24:            $("#bindLink").bind("click", function() {
  25:                 alert("You clicked the link!");
  26:            }); 
  27:            $(".bind2").bind("click", function() {
  28:                 alert("You clicked the element with tagName: " + this.tagName);
  29:            }); 
  30:            $("#bindDiv").bind("click", function() {
  31:                 $(this).append("<br />Clicked me....");
  32:            });            
  33:         });
  34:     </script>
  35: </body>
  36: </html>

In this sample I use the method

$(document).ready(function() { });

This makes sure that the DOM tree has been fully loaded before the code in the function runs. This is great place to put code that should run once in the page.

To bind an event you use the bind(event, function) method. The event is specified as a string without the ‘on’ in the beginning and all lower case characters.

Some of the available events are:

  • click
  • dblclick
  • mouseenter
  • mouseleave
  • mousemove
  • etc… (check out the events section on http://docs.jquery.com)

To bind the click event to an element with an id of ‘bindLink’ I write the following:

$("#bindLink").bind("click", function() {
     alert("You clicked the link!");
}); 

 

You can create a separate function but an inline anonymous function works just as well.

If I want to access the element that was clicked inside the function I can do so via the ‘this’ keyword:

$(".bind2").bind("click", function() {
     alert("You clicked the element with tagName: " + this.tagName);
}); 

Inside of the function ‘this’ will refer to the element that was clicked. One thing to note is that it refers to the DOM element, not the jQuery object. If I want to have a jQuery object wrapped around the element I need to write $(this).

$("#bindDiv").bind("click", function() {
     $(this).append("<br />Clicked me....");
}); 

Here we use the .append(html) method will add the html string to the end of the contents of the element. If you wanted to insert content before the content you could have used .prepend(html). There are also the methods .before(html)  and .after(html) that will add content before and after the DOM element itself.

Mouse over and out

sample 2 - mouse enter and leave.htm

   1: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   2: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   3: <html xmlns="http://www.w3.org/1999/xhtml" >
   4: <head>
   5:     <title>jQuery sample 2 - mouse enter and leave</title>
   6:     <script type="text/javascript" src="jquery-1.2.6.min.js"></script>
   7:     <style type="text/css">
   8:         .hoverDiv { font-size: 2em; padding: 1em; width: 23em; text-align: center; }
   9:         .hovering { background-color: #faebeb;color: #fa0000; }
  10:     </style>
  11: </head>
  12: <body>
  13:     <div class="hoverDiv">
  14:         1. Move the mouse over me to make cool stuff happen. :)
  15:     </div>
  16:     <div class="hoverDiv">
  17:         2. Move the mouse over me to make cool stuff happen. :)
  18:     </div>
  19:     <div class="hoverDiv">
  20:         3. Move the mouse over me to make cool stuff happen. :)
  21:     </div>
  22:     <script type="text/javascript">
  23:         $(document).ready(function() {
  24:             $(".hoverDiv")
  25:                 .bind("mouseenter", function() {
  26:                     $(this).addClass("hovering");
  27:                 })
  28:                 .bind("mouseleave", function() {
  29:                     $(this).removeClass("hovering");
  30:                 })
  31:                 .bind("click", function() {
  32:                     alert("My text is: " + $(this).text());
  33:                 });
  34:         });
  35:     </script>
  36: </body>
  37: </html>

In this sample I’ve used the mouseenter and mouseleave events to create a hover effect. The list of divs all have a specific class so that I can bind to them all at once.

I then chain together multiple bind methods to make sure we handle enter, leave and click events. The click event just tells us what text the div we clicked contains.

To create the hover effect I use the handy methods addClass and removeClass. These are great to create these kinds of effects. There is also a toggleClass that will alternately add and remove the class.

Special click event – Toggling

If you want to switch between two different states of an element there is an alternative to bind that is called toggle(function1, function2).

It will alternately call function1 and function2 when you click the element. Here’s a sample where we turn on and off list elements.

sample 3 - toggle event.htm

   1: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   2: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   3: <html xmlns="http://www.w3.org/1999/xhtml" >
   4: <head>
   5:     <title>jQuery sample 3 - toggle event</title>
   6:     <script type="text/javascript" src="jquery-1.2.6.min.js"></script>
   7:     <style type="text/css">
   8:         li { width: 30px; border: solid 1px black; text-align: center; }
   9:         .on { background-color: Yellow; font-weight: bold; }
  10:     </style>
  11: </head>
  12: <body>
  13:     <ul>
  14:         Click to turn on/off
  15:         <li>Off</li>
  16:         <li>Off</li>
  17:         <li>Off</li>
  18:         <li>Off</li>
  19:     </ul>
  20:     <script type="text/javascript">
  21:         $(document).ready(function() {
  22:             $("ul li").toggle(function() {
  23:                 $(this).text("On").addClass("on");
  24:             }, function() {
  25:                 $(this).text("Off").removeClass("on");
  26:             });            
  27:         });
  28:     </script>
  29: </body>
  30: </html>

Here we alternately change the text, and look, of the list elements between on and off.

Creating a table with selectable rows

We’ll finish off the examples of event handling by creating a table where the user has the ability to select rows. This could for instance be used to create a simple online file manager.

sample 4 - selecting table rows.htm

 

 

   1: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
   2: "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   3: <html xmlns="http://www.w3.org/1999/xhtml" >
   4: <head>
   5:     <title>jQuery sample 4 - selecting table rows</title>
   6:     <script type="text/javascript" src="jquery-1.2.6.min.js"></script>
   7:     <style type="text/css">
   8:         table, td, th { border: solid 1px black; border-collapse: collapse; 
   9:                         padding: 4px; }
  10:         .selected td { background-color: Yellow; }
  11:         .hovering td { background-color: #ebebeb; }
  12:     </style>
  13: </head>
  14: <body>
  15:     <table id="files">    
  16:         <colgroup>
  17:             <col style="width: 300px;" />
  18:             <col style="width: 100px; text-align: right;" />
  19:             <col style="width: 100px; text-align: right;" />
  20:         </colgroup>
  21:         <tr><th>Filename</th><th>File size</th><th>Last modified</th></tr>
  22:         <tr><td>image1.jpg</td><td>56 KB</td><td>2005-12-01</td></tr>
  23:         <tr><td>image3.gif</td><td>114 KB</td><td>2005-12-05</td></tr>
  24:         <tr><td>flowers.jpg</td><td>23 KB</td><td>2005-08-12</td></tr>
  25:         <tr><td>happy people.png</td><td>94 KB</td><td>2005-06-23</td></tr>
  26:         <tr><td>stuff.jpg</td><td>312 KB</td><td>2005-03-12</td></tr>
  27:     </table>
  28:     <ol id="selected">
  29:         You have selected the following files
  30:     </ol>
  31:     <script type="text/javascript">
  32:         $(document).ready(function() {
  33:             $("#files tr:has(td)")
  34:                 .bind("click", function() {
  35:                     $(this).toggleClass("selected");
  36:                     UpdateSelectedList();
  37:                 })
  38:                 .bind("mouseenter", function() {
  39:                     $(this).addClass("hovering");
  40:                 })
  41:                 .bind("mouseleave", function() {
  42:                     $(this).removeClass("hovering");
  43:                 });
  44:         });        
  45:         function UpdateSelectedList()
  46:         {
  47:             $("#selected li").remove();
  48:             $("#files .selected").each(function () {
  49:                 $("#selected").append(CreateFileItem($(this)));
  50:             });
  51:         }        
  52:         function CreateFileItem(element)
  53:         {
  54:             return "<li>" + element.find("td:first").text() + "</li>";
  55:         }        
  56:     </script>
  57: </body>
  58: </html>

Here we add a simple table with a few rows. The table could be the output of a repeater control that lists the contents of a directory. Beneath the table we have an ordered list where we display the files that we have selected.

When you look at it in the browser it looks quite complex, but as you see the javascript code is really simple.

If you take a look at the selector we use a filter for the table rows. tr:has(td) will only select the table rows that has td-tags as children. This will filter away the first row that is our header row.

We then use the click event to toggle the class “selected” which will update the background color. It then calls the function UpdateSelectedList(); which updates the list of selected files.

function UpdateSelectedList()
{
    $("#selected li").remove();
    $("#files .selected").each(function () {
        $("#selected").append(CreateFileItem($(this)));
    });
}   

 

We begin by selecting all list items and remove them. Then we select all table rows that has the css class “selected” and run the .each(function) function on them. This is the same as foreach() in .NET. For every selected table row we append a new list item to list.

function CreateFileItem(element)
{
    return "<li>" + element.find("td:first").text() + "</li>";
}      

To get the name of the selected file we use the filter :first which selects only the first matched element and the get the name with .text().

And that’s pretty much it.  The only other code we have is the mouseenter and mouseleave events to get a nice hover effect over the table rows.

This is beauty of jQuery, with really simple code you can create really impressive results that seem much more complex than they are. And since jQuery handles all cross browser issues it will work in all modern browsers.

If you compare this solution with the classic ASP.NET solution, which would be performing a postback on every click, you must agree that this is much more elegant and not that much harder to code.

As usual I recommend downloading the samples and play around with them. Also you should check out http://docs.jquery.com, especially the events section.

jQuery samples - part 2.zip (19,70 kb)


Currently rated 2.5 by 2 people

  • Currently 2.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Related posts

Comments

January 25. 2009 12:15

A nice and interesting post! Thanks for the read. A suggestion: Since you have a lot of examples which could be run by the browser, why don't you also show how they look when run? Att the DOM elements necessary and add the scripts so that the visitor, e.g. me, can click and drag and test whatever the scripts are supposed to do?

Robert

March 12. 2009 09:33

Great article. I would also recommend you show the demo on your site as well. We understand the code by would like to see it in action before we try it out.

Thanks

Hassan

March 13. 2009 02:44

That's a good suggestion, I'll put up the files so you can try it out. Since it's just static HTML + javascript I can just put up the files on the site and you can try it out.

Mats

July 6. 2009 06:48

Very useful post, all the events described are very consistent and clear, I will do everything as you describe.

Removal

July 31. 2009 22:50

finally i find something that i want to know..
thanks for this usefull informations..

tagged comments

September 14. 2009 09:51

I havent any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us.

payday online

September 15. 2009 00:59

I havent any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us.

payday online

September 21. 2009 01:06

We are a group of volunteers and starting a new initiative in a community. Your blog provided us valuable information to work on.You have done a marvellous job!

payday loans

September 21. 2009 14:10

We are a group of volunteers and starting a new initiative in a community. Your blog provided us valuable information to work on.You have done a marvellous job!

payday loans

September 29. 2009 09:00

I am involved in css style sheet coding and website / element positioning at the moment and got drawn by your post, " jQuery part 2 ndash Event handling " , in the search engines. The problems of using a style sheet to produce a satisfactory page in all the leading browsers, Internet Explorer, Safari, Firefox and Google Chrome is a big head ache which takes me numerous hours to master. Interesting to read your thoughts and the comments in your website on the matter. I feel the tutorial websites are inflexible and address the same items, dialog in web logs oftentimes addresses actual ways to overcome issues or the better ways to approach online design. Thank you for the article.

Drain cleaning

October 29. 2009 03:43

i like

ed hardy shoes

November 4. 2009 06:50

good post Thank for sharing

scratch and dent

November 14. 2009 02:53

Thank you for the sensible critique. Me and my neighbor were just preparing to do some research about this. We got a grab a book from our local library but I think I learned more from this post. I am very glad to see such great information being shared freely out there.

Restaurant Recipes

November 21. 2009 05:23

Searching for this for some time now - i guess luck is more advanced than search engines Smile

faxless payday loans

November 25. 2009 07:32

Great blog. Do you know of any relevant forums or discussion groups?

Wendy Xavier

November 25. 2009 10:08

I've been researching the World Wide Web for my research on this subject. I'm so thankful what you shared adds a new attribute to the information I'm compiling. I truly appreciate the way which you look at this subject field, it extend to me a unusual means of looking at it now. Thanks for the share.

Anna @ online flower

November 25. 2009 12:02

I was very happy that I found this site. I wanted to thank you for this great information!! I definitely enjoyed every bit of it and I have you bookmarked your blog to check out the new stuff you post in the future.

learn guitar

November 27. 2009 01:34

This is by far one of the neatest written articles on this field. I was researching on the exact aforesaid field and your position entirely took me off with the way you see this topic. I compliment your insight but do allow me to come back to comment further as I'm presently enlarging my research on this field further. I will be back to join in this discussion as I've bookmarked and tag this very page.

Tisha @ internet florists

November 27. 2009 01:49

Its cool... I always like to know about some technology specific interesting topics....

Annuity Reviews

November 27. 2009 05:56

Enjoying your blog. My main income is based on seo. Not many are getting the way Search Engine Optimization has to be done the right way. Backlinks are a factor of SEO, many people are spamming sites and hurt their rankings. I write about SEO almost every day and if you want more info feel free to go there and leave your comments! Again great info here and keep it up ;)

seo software download

November 27. 2009 07:16

Thanks for sharing another good piece of information. Best regards, Lottie Chamberlane @ Hårförlängning

hårförlängning

November 27. 2009 10:12

Doing a little research. Your post helped me – thanks. Outstanding, Rebecca Barber @ Flyttstädning

Flyttstädning

November 27. 2009 11:57

I was rationalizing on this topic last evening and I determined to search the World Wide Web for some information. Your blog came up in my search and I'm impress what you have penned on this field. As I'm currently expanding my research and thus cannot chip in further, however, I've bookmarked it and will be returning to further comment. Like I said, love this comment and will be back soon.

catherine @ a florist

November 28. 2009 01:34

hi,

RemoveAcne

November 28. 2009 09:26

Hmmm interesting stuff

cash loans

November 29. 2009 07:41

Hi buddy, superb blog post! Pls continue this great work!!!!

addicting games

December 2. 2009 11:28

Comfortabl y, the post is really the sweetest on this notable topic. I fit in with your conclusions and will eagerly look forward to your upcoming updates. Just saying thanks will not just be enough, for the phenomenal lucidity in your writing. I will directly grab your rss feed to stay abreast of any updates. De lightful work and much success in your business endeavors!

Issac Maez

December 3. 2009 14:48

I was rationalizing on this topic last evening and I determined to search the World Wide Web for some information. Your blog came up in my search and I'm impress what you have penned on this field. As I'm currently expanding my research and thus cannot chip in further, however, I've bookmarked it and will be returning to further comment. Like I said, love this comment and will be back soon.

Cheap auto insurance quotes

December 7. 2009 15:57

I wanted to thank you for this excellent read!! I definitely loved every little bit of it. I have you bookmarked your site to check out the latest stuff you post.

Free Articles

December 7. 2009 16:30

Hey there! I have been lurking for a while now on your blog and finally wanted to get the courage up to mention thanks to you. You have inspired me to begin my own blog and it has been going ok so far. I am trying to begin an article directory, but am not certain if that can eventually work or not. Anyways..thanks for your good insight into this crazy blogging world!

five point star tattoo

December 10. 2009 06:32

In searching for sites related to web hosting and specifically comparison hosting linux plan web, your site came up.You are a very smart person!

easy personal loans

December 12. 2009 16:10

I was looking for this the other day. i dont usually post in forums but i wanted to say thank you!

payday loans

December 14. 2009 00:01

Great way to explain it. Can't say more than to appreciate what you are penned down. can you show how to grab your rss feed? I couldn't find how.

price resveratrol

December 15. 2009 14:57

I am glad that I found your site. I wanted to thank you for this great read!! I definitely enjoying every bit of it and I have you bookmarked to check out the new stuff you post.

stop panic attacks

December 18. 2009 18:35

I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own BlogEngine blog now. Really the blogging is spreading its wings rapidly. Your write up is a fine example of it.

Tomato Soup Recipes

December 18. 2009 22:39

Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me.

Kitchen appliance reviews

December 19. 2009 23:38

I just love this BlogEngine platform, it makes a blog look and act like a blog if you ask me. Do you prefer it over WordPress and Blogger?

bread machine reviews

December 20. 2009 16:12

I heard there is a new solitaire game. My close friend told me about it, and I really think it's the best solitaire game ever made! I got it here: <a href="http://www.funsolitairegame.com/">Get" rel="nofollow">http://www.funsolitairegame.com/">Get The Solitaire Game</a> http://www.funsolitairegame.com/

Isidro Baymon

December 21. 2009 04:59

Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me.

online casinos proudly

December 21. 2009 23:35

I am stricken by the way you embraced this topic. It is not often I come across a website with interesting articles like yours. I will bookmark your feed to keep up to date with your upcoming updates.Just striking and do continue up the good work.

Alia Weatherly

December 22. 2009 15:23

Simple and to the point. Perfectly well done. I think I will be coming back if the rest of your posts are like this.

Marcia Moerbe

December 22. 2009 19:31

There are certainly a lot of details like that to take into consideration. That is a great point to bring up. I offer the thoughts above as general inspiration but clearly there are questions like the one you bring up where the most important thing will be working in honest good faith. I don?t know if best practices have emerged around things like that, but I am sure that your job is clearly identified as a fair game.

eagle idaho homes for sale

December 23. 2009 00:14

I thought it was going to be some boring old post, but it really compensated for my time. I will post a link to this page on my blog. I am sure my visitors will find that very useful.

symbol barcode scanner

December 23. 2009 01:55

Hi, I run across this website by accident when I was going through Google then I popped in to your site. I have to say your web site is interesting I love your theme! I currently don’t have a lot of time at the current moment to read through your sitebut I have bookmarked it. I will come back in a day or two. Thanks for a great site.

Joey

December 23. 2009 05:59

Generally I do not make a comment on blogs, but I have to mention that this post really forced me to do so. Really nice post!

Scotty

December 23. 2009 09:27

I’m definitely bookmarking this site. Really great articles. Do you recommend any other readings?

Lea Miyasato

December 23. 2009 14:00

In general I do not post on blogs, but I would like to say that this post really forced me to do so. Really nice post!

Silly Mae

December 23. 2009 17:39

This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! keep up the good work.

Bryce Brian

December 23. 2009 20:11

In general I don’t post on blogs, but I have to mention that this post really forced me to do so. Really nice post!

Sam

December 24. 2009 01:37

Nice to see you make a post on this topic, I need to book mark this site. Keep up the good work.

Spara

December 24. 2009 05:43

Advantageously, the post is in reality the best on this deserving topic. I agree with your conclusions and will thirstily look forward to your future updates. Just saying thanks will not just be enough, for the fantasti c lucidity in your writing. I will directly grab your rss feed to stay informed of any updates. Pleasant work and much success in your business efforts!

Scotty

December 24. 2009 13:47

I go to your website on occasion and I must say that I like your template!

saunders

December 24. 2009 14:15

Aw, this was a really quality post. In theory I'd like to write like this too - taking time and real effort to make a good article... but what can I say... I procrastinate alot and never seem to get something done.

lunettes vue

December 24. 2009 16:39

I go to your website from time to time and I must mention that I like your template!

Silly Mae

December 24. 2009 16:48

Merry xmas and happy new year to all of you.

articles directory

December 24. 2009 23:02

Usually I don’t make a comment on blogs, but I would like to mention that this post really forced me to do so. Really nice post!

Sam

December 24. 2009 23:18

Substantially, the post is actually the greatest on this noteworthy topic. I concur with your conclusions and will thirstily look forward to your coming updates. Saying thanks will not just be enough, for the tremendous lucidity in your writing. I will instantly grab your rss feed to stay privy of any updates. Fabulous work and much success in your business dealings!

Sam

December 25. 2009 11:31

Found your site on del.icio.us today and really liked it.. i bookmarked it and will be back to check it out some more later ..

fast payday loans

December 25. 2009 14:53

This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! keep up the good work.

Abbey Gohn

December 25. 2009 17:58

I had hard time reading your blog with firefox, you would better update your blog

sexe francais

December 25. 2009 20:14

Nice to see you make postings on this topic, I should book mark this site. Just keep up the good work.

Mike

December 26. 2009 03:05

This is actually a Great knowledge gaining news and all thanks to google search engine get me on here. I enjoyed reading your news and added to the favorites. The views you tried to put up was clearly understandable. My sister also appreciated after reading this article. I will read for more sooner. bye - Sim

Watch Free Movies

December 26. 2009 04:01

In general I do not make a comment on blogs, but I would like to mention that this post really forced me to do so. Really nice post!

Sam

December 26. 2009 14:13

thanks for sharing

exchange rate widget

December 26. 2009 14:14

I like it@!

exchange rate widget

December 26. 2009 14:14

nice !

currency converter widget

December 26. 2009 14:14

thanks!

currency converter widget

Add comment


 

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

August 1. 2010 03:16