Javascript event delegation


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  2.  
  3. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  4. <head>
  5. <title>Javascript Event Delegation Test</title>
  6.  
  7. <style type="text/css">
  8. body {
  9. padding: 10px;
  10. }
  11. table {
  12. border: solid 1px black;
  13. }
  14. table td {
  15. padding: 3px;
  16. }
  17. </style>
  18.  
  19. <script type="text/javascript">
  20. window.onload = function() {
  21. // Old
  22. var rows = document.getElementById("old").getElementsByTagName("tr");
  23. for (var i = 0, ln = rows.length; i < ln; ++i) {
  24. rows[i].onclick = function() {
  25. alert("Row Index: " + this.rowIndex);
  26. }
  27. }
  28.  
  29. // New
  30. function getTarget(x){
  31. x = x || window.event;
  32. return x.target || x.srcElement;
  33. }
  34.  
  35. document.getElementById("new").onclick = function(e) {
  36. var root = this;
  37. var t = getTarget(e);
  38.  
  39. while (t != root) {
  40. if (t.nodeName.toLowerCase() == "tr") {
  41. alert("Row Index: " + t.rowIndex);
  42. break;
  43. }
  44.  
  45. t = t.parentNode;
  46. }
  47. };
  48. };
  49. </script>
  50. </head>
  51.  
  52. <body>
  53.  
  54. <strong>To test: Click on a table row.</strong>
  55.  
  56. <h3>Attaching event to each row:</h3>
  57. <table id="old">
  58. <tr>
  59. <td>One</td>
  60. <td>Two</td>
  61. <td>Three</td>
  62. </tr>
  63. <tr>
  64. <td>One</td>
  65. <td>Two</td>
  66. <td>Three</td>
  67. </tr>
  68. <tr>
  69. <td>One</td>
  70. <td>Two</td>
  71. <td>Three</td>
  72. </tr>
  73. <tr>
  74. <td>One</td>
  75. <td>Two</td>
  76. <td>Three</td>
  77. </tr>
  78. <tr>
  79. <td>One</td>
  80. <td>Two</td>
  81. <td>Three</td>
  82. </tr>
  83. </table>
  84.  
  85. <h3>Attaching event to table:</h3>
  86. <table id="new">
  87. <tr>
  88. <td>One</td>
  89. <td>Two</td>
  90. <td>Three</td>
  91. </tr>
  92. <tr>
  93. <td>One</td>
  94. <td>Two</td>
  95. <td>Three</td>
  96. </tr>
  97. <tr>
  98. <td>One</td>
  99. <td>Two</td>
  100. <td>Three</td>
  101. </tr>
  102. <tr>
  103. <td>One</td>
  104. <td>Two</td>
  105. <td>Three</td>
  106. </tr>
  107. <tr>
  108. <td>One</td>
  109. <td>Two</td>
  110. <td>Three</td>
  111. </tr>
  112. </table>
  113.  
  114. </body>
  115.  
  116. </html>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.