Fuxi
Fuxi

Reputation: 7599

jquery: odd/even row elements + hover

i'm styling a table with this command:

$("tr").filter(":odd").addClass("odd");

works nice. now i'm having a hover function which would show a cursor when i move the cursor over a row.

the problem: on hover-out i want the table row getting back its "odd" class again, in order to keep the 2-colored layout. unfortunately it doesnt work - hovering-out will result in a plain class.

here's my hovering-code:

function hover = function(tr,cod)
{
    if(cod)
    {
        tr.addClass("hover");
    }else{
        if(tr.is(":odd"))
        {
            tr.addClass("odd");
        }else{
            tr.removeClass();
        }
    }
}

anyone can tell me what's wrong?

thx in advance.

Upvotes: 0

Views: 2409

Answers (3)

user791129
user791129

Reputation: 111

you dont need to remove all class added. just use !important in your css for hover class. it will override the odd class.

.hover {background-color:green !important;}
.odd {background-color:blue}

$("#datatable tr:odd").addClass("odd"); 
$("#datatable tr").mouseover(function() { $(this).addClass("hover"); });
$("#datatable tr").mouseout(function() { $(this).removeClass("hover"); });

Upvotes: 1

Fabian Vilers
Fabian Vilers

Reputation: 2982

You should use toggleClass() instead of addClass() + removeClass().

Upvotes: 2

Greg
Greg

Reputation: 321688

I think you want this instead:

function hover = function(tr,cod)
{
    if(cod)
    {
        tr.addClass("hover");
    }else{
        tr.removeClass("hover");
    }
}

Calling removeClass() is removing all the classes. Since nodes can have multiple classes applied it's fine to just add and remove the hover class, whether it's odd or not.

Upvotes: 3

Related Questions