I am new to javascript and for practice, I am using javascript to stripe even rows for tables with a particular class. Besides that, I am trying to create a ‘hover’ effect on table rows using javascript only.
I was able to create the onmouseover effect, however, I am having a very difficult time going back to the default style onmouseout of the table row.
Please keep in mind that I know this can easily be achieved with css or JQuery; however, for this, I would like to stick to javscript only.
What I tried:
function alternate(){
var tables = document.getElementsByTagName("table");
//apply the code to ALL tables on the page with a particular class
for (var ti = 0; ti < tables.length; ++ti) {
if (tables[ti].className == "striped"){ //stripe tables
var rows = tables[ti].getElementsByTagName("tr");
for(i = 0; i < rows.length; i++){
//change style of even rows to create striped effect
if(i % 2 == 0){
rows[i].className += "even"; //stripe even rows while maintaining default style to odd rows
}
rows[i].onmouseover = function() {
this.className="";
this.className="hovered";
}
rows[i].onmouseout = function() {
if(i % 2 == 0){
this.className="even";
}else{
this.className="odd";
}
}
}
}
}
}
I’m not sure if I quite understood your question, but I have created a jsfiddle which does what I think you meant.
The problem, from what I could tell, was that when row[i].mouseout is triggered, the value of i is the number of tables rows in your table. The fix is, to save the original classname on mouseover, and then re-assign that classname onmouseout. Here is the fiddle. http://jsfiddle.net/LBaZu/4/
Edit: I re-read your question and it occurred to me that you only wanted to set the odd table rows classname to odd on mouseout, not before.