0


Hope my title is not too confusing. Please let me know if there is a better way to title my problem.
I have jQuery function applying background-color to the odd rows in a table and on hover change the color to red. But if I edit the table dynamically my jQuery does not work any more.
I read a lot about JS event delegation and could not find any information about how to make this work without having actual event...

$(document).ready(function(){
    //add background-color to all odd rows
    //very important!!!
    $("#tab3 tbody tr:odd").css("background-color", "#DCF1FD");
    //change color on hover 
    //less important!!!     
    $("#tab3 tbody tr").hover(
      function () {
        $(this).css("color", "red");
      },
      function () {
        $(this).css("color", "#000");
      }
    );
});

Is there a way to make it work after I edit the table.

EDIT:
This must work on IE8

Radi
  • 271
  • 6
  • 19

2 Answers2

1

use jQuery delegate on the table that will work even if you update the table rows dynamically because the event is attached to table and not each rows of it.

$(document).ready(function(){
    $("#tab3 tbody tr:odd").css("background-color", "#DCF1FD");


    $("#tab3").delegate('tbody tr', 'hover', function(){
        $(this).css("color", "red");
      },
      function () {
        $(this).css("color", "#000");
    });
});

If you are updating the whole table dynamically then use this

$(document).delegate('#tab3 tbody tr', 'hover', function(){
        $(this).css("color", "red");
      },
      function () {
        $(this).css("color", "#000");
 });

You can set the background color of odd row with simple css

#tab3 tbody tr:nth-child(odd)
{ 
   background: #DCF1FD; 
}
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
0

... Or you could just use CSS to define the backgrounds for even rows, odd rows and the hover state. Se the first answer to this question. (EDIT: fixed link, it was pointing the wrong SO thread).

Community
  • 1
  • 1
bfavaretto
  • 71,580
  • 16
  • 111
  • 150
  • No, not even IE9 according to [this table](http://msdn.microsoft.com/en-us/library/cc351024(v=vs.85).aspx). :( – bfavaretto Aug 16 '11 at 20:54
  • Sorry, I linked the wrong SO article. Will edit the link. What I meant was actually `:nth-child(even)` and `:nth-child(odd)`. IE support begins in IE9, I think. – bfavaretto Aug 16 '11 at 20:56
  • I already know about these CSS selectors [LINK](http://www.w3.org/Style/Examples/007/evenodd). – Radi Aug 16 '11 at 21:08