DOM Scripting vs jQuery 4: Row Highlighting


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



Copy this code and paste it in your HTML
  1. /*HTML*/
  2. <table border="1">
  3. <tr>
  4. <td>1111111111</td>
  5. <td>1111111111</td>
  6. <td>1111111111</td>
  7. <td>1111111111</td>
  8. </tr>
  9. <tr>
  10. <td>2222222222</td>
  11. <td>2222222222</td>
  12. <td>2222222222</td>
  13. <td>2222222222</td>
  14. </tr>
  15. <tr>
  16. <td>3333333333</td>
  17. <td>3333333333</td>
  18. <td>3333333333</td>
  19. <td>3333333333</td>
  20. </tr>
  21. <tr>
  22. <td>4444444444</td>
  23. <td>4444444444</td>
  24. <td>4444444444</td>
  25. <td>4444444444</td>
  26. </tr>
  27. <tr>
  28. <td>5555555555</td>
  29. <td>5555555555</td>
  30. <td>5555555555</td>
  31. <td>5555555555</td>
  32. </tr>
  33. </table>
  34.  
  35. /*CSS*/
  36. .highlight {
  37. background-color: red;
  38. color: white;
  39. }
  40.  
  41.  
  42. /*DOM Scripting*/
  43. function addLoadEvent(func) {
  44. var oldonload = window.onload;
  45. if (typeof window.onload != 'function') {
  46. window.onload = func;
  47. } else {
  48. window.onload = function() {
  49. oldonload();
  50. func();
  51. }
  52. }
  53. }
  54.  
  55. function addClass(element,value) {
  56. if (!element.className) {
  57. element.className = value;
  58. } else {
  59. newClassName = element.className;
  60. newClassName+= " ";
  61. newClassName+= value;
  62. element.className = newClassName;
  63. }
  64. }
  65.  
  66. function highlightRows() {
  67. if(!document.getElementsByTagName) return false;
  68. var rows = document.getElementsByTagName("tr");
  69. for (var i=0; i<rows.length; i++) {
  70. rows[i].oldClassName = rows[i].className
  71. rows[i].onmouseover = function() {
  72. addClass(this,"highlight");
  73. }
  74. rows[i].onmouseout = function() {
  75. this.className = this.oldClassName
  76. }
  77. }
  78. }
  79.  
  80. addLoadEvent(highlightRows);
  81.  
  82. /*jQuery*/
  83. $(document).ready(function(){
  84. $('tr').mouseover(function(){$(this).addClass('highlight');}).mouseout(function(){$(this).removeClass('highlight');});
  85. });

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.