user669677
user669677

Reputation:

animated highlighting of table row using jquery

I would like to change (animated) the color of the table row if the mouse is over it. Could you help me to do this? Thanks.

td{width:200px;text-align:center; background-color:gray;}


$('tr').mouseover(function() {
    $(this).animate
        ({ backgroundColor: "red" }, 1000);
});

$('tr').mouseout(function() {
    $(this).animate
        ({ backgroundColor: "gray" }, 1000);
});

http://jsfiddle.net/NXejr/10/

Upvotes: 3

Views: 7194

Answers (5)

fearofawhackplanet
fearofawhackplanet

Reputation: 53466

You have two problems:

You're animating the color of tr, but this is over-ridden by your td styling.

Change to

$('tr').mouseover(function() {
    $(this).find('td').animate
        ({ backgroundColor: "red" }, 1000);
});

Will get the mouseover working.

For some reason jQuery isn't liking gray in the mouseout function. Not sure why that is, but it will work if you change to for example

$('tr').mouseout(function() {
    $(this).find('td').animate
        ({ backgroundColor: "#aaa" }, 1000);
});

I also prefer using the hover solution a couple of the other suggested, but they didn't address these issues

Upvotes: 0

Chris Pratt
Chris Pratt

Reputation: 239470

$('tr').mouseover(function() {
    $('td', this).stop(true, true).animate
        ({ backgroundColor: "red" }, 1000);
});

$('tr').mouseout(function() {
    $('td', this).stop(true, true).animate
        ({ backgroundColor: "#666" }, 1000);
});

http://jsfiddle.net/MtF6E/

Table rows don't respond to background color, so you change the background of the tds inside, instead. And for some reason it doesn't like "gray" at all. Thought that was actually a valid CSS color name, but apparently not. I used "#666" instead and it worked fine. I also introduced stop(true, true). That will stop any in progress animation on the element, so the current one can go ahead. It leads to a smoother look and response.

Upvotes: 4

Rafay
Rafay

Reputation: 31043

$("table tr ").hover(
    function(){
        $(this).animate
        ({ backgroundColor: "Red" }, 1000);
    },
    function(){
        $(this).stop(true,true).animate
        ({ backgroundColor: "White" }, 1000);
    }
);

use .stop(true,true) to prevent the animation from occurring if the mouse is hovered frequently

http://jsfiddle.net/NXejr/13/

Upvotes: 1

Goran
Goran

Reputation: 3410

Try using hover instead of mouseover and mouseout:

$('tr').hover(function() {
    $(this).animate({ "background-color" : "red" }, 1000);
},
function () {
    $(this).animate({ "background-color" : "gray" }, 1000);
});

Upvotes: 0

wanovak
wanovak

Reputation: 6127

$('tr td').mouseover(function(){
    $(this).css('background-color','#f00');
}).mouseout(function(){
    $(this).css('background-color','#444');
});

http://jsfiddle.net/Jp4AP/

Upvotes: 0

Related Questions