santa
santa

Reputation: 12512

Highlight row with jQuery

I'd like to have a function that will highlight row of the table when a mouse rolls over it. I currently have a function that creates an alternate row color every other row and I would like to modify it rather than creating a separate function. Here's what I have:

$(".tblRows tr:even").addClass("altColor");

where

.altColor TD {
background-color:#f5f5f5
}

and my HTML is

<table class="tblRows">
...

I know there's a jQuery function hover() but I'm not sure how to incorporate it with what I've got. When hovered I'd like it to use class="hilite"

Is it possible?

Upvotes: 1

Views: 808

Answers (4)

user113716
user113716

Reputation: 322502

Is there a reason you don't just use CSS for this?

#myTable tr:hover {
    background: orange;
}

Won't work on a <tr> in IE6, but will work elsewhere.

Example: http://jsfiddle.net/auWGU/

Upvotes: 2

Andrew Whitaker
Andrew Whitaker

Reputation: 126052

Using hover:

$(".tblRows tr").hover(function() {
    $(this).addClass("hilite");
}, function() {
    $(this).removeClass("hilite");
});

Which is shorthand for:

$(".tblRows tr").mouseenter(function() {
    $(this).addClass("hilite");
}).mouseleave(function() {
    $(this).removeClass("hilite");
});

Example here: http://jsfiddle.net/andrewwhitaker/kQvJ3/

Upvotes: 1

Christian Joudrey
Christian Joudrey

Reputation: 3461

$('.tblRows tr')
    .mouseenter(function() { $(this).addClass('hilite'); })
    .mouseleave(function() { $(this).removeClass('hilite'); };

Upvotes: 2

Simon
Simon

Reputation: 381

You need the hover-function to add a mouse-over-event-handler to each row in your table. E.g:

$('.tblRows tr').hover(function () {
    $(this).toggleClass('hilite');
},
function () {
    $(this).toggleClass('hilite');
});

Upvotes: 1

Related Questions