Posted By

Meander365 on 11/04/10


Tagged

javascript event jquery delegation


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

kubaitis
superman


jQuery Event Delegation - Simple Example


 / Published in: jQuery
 

URL: http://brandonaaron.net/blog/2010/03/4/event-delegation-with-jquery

Allow events to bubble up the DOM to overseeing handlers.

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
  5. <title>Event Delegation</title>
  6. </head>
  7. <body>
  8.  
  9. <script type="text/javascript" src="_assets/behaviour/jquery-1.4.3.min.js"></script>
  10. <script type="text/javascript">
  11. $(function() {
  12.  
  13. //delegate
  14. $('table').delegate('tr','click', function() {
  15. $(this).toggleClass('selected');
  16. });
  17.  
  18. //normal bind - slower performance as each tr has to have a bind event
  19. //$('tr').bind('click', function() {
  20. //$(this).toggleClass('selected');
  21. //});
  22.  
  23. });
  24. </script>
  25.  
  26. <style type="text/css">
  27. .selected {background:yellow;}
  28. </style>
  29.  
  30. <table cellspacing="0">
  31. <tbody>
  32. <tr>
  33. <td>1</td>
  34. <td>Lorem ipsum dolor sit amet</td>
  35. </tr>
  36. <tr>
  37. <td>2</td>
  38. <td>Lorem ipsum dolor sit amet</td>
  39. </tr>
  40. <tr>
  41. <td>3</td>
  42. <td>Lorem ipsum dolor sit amet</td>
  43. </tr>
  44. <tr>
  45. <td>4</td>
  46. <td>Lorem ipsum dolor sit amet</td>
  47. </tr>
  48. <tr>
  49. <td>5</td>
  50. <td>Lorem ipsum dolor sit amet</td>
  51. </tr>
  52. <tr>
  53. <td>6</td>
  54. <td>Lorem ipsum dolor sit amet</td>
  55. </tr>
  56. </tbody>
  57. </table>
  58.  
  59.  
  60. </body>
  61. </html>

Report this snippet  

You need to login to post a comment.