Khuram Malik
Khuram Malik

Reputation: 1485

CSS for Hover only applied to odd rows with jQuery

I've got this bit of code, which works fine for alternating the actual rows, but only hovers on the "odd" rows.

I'm using the following code:

    <script type="text/javascript"> 
$(document).ready(function(){
    //jQuery ready is quicker than onload
$(".stripeMe tr").mouseover(function(){$(this).addClass("over");}).mouseout(function(){$(this).removeClass("over");});
$(".stripeMe tr:even").addClass("alt");
});

This is the css that I'm using

    #table tr.over td{background: #bcd4ec;}
    #table tr.alt td {background: #ecf6fc;}

Any ideas?

Upvotes: 2

Views: 1386

Answers (4)

Rob
Rob

Reputation: 7717

You don't need jQuery/Javascript to manage this. As yoavmatchulsky mentions, change your CSS, but instead of an over class, use :hover

#table tr td { /* regular */ }
#table tr.alt td { /* regular */ }

#table tr:hover td { background: #bcd4ec; }
#table tr.alt:hover td { background: #ecf6fc; }

EDIT: Since it's required to use jQuery, this may not work to answer the OP. This would be faster than using jQuery IMO, though. jQuery will have to find and update the behavior on multiple elements on the page (e.g., table rows) to apply the behavior.

Upvotes: 0

JAiro
JAiro

Reputation: 5999

here you have the example wotking, the problem was the herarchy of the css, now is working because the over class y down. In this case the over class will replace the alt class.

<html>
<head>
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.5b1.js"></script>
</head>
<body>
  <style>
    #table tr.alt { background: #ecf6fc;}
    #table tr.over { background: red;}
  </style>
<table id="table" class="stripeMe">
  <tr>
    <td>aaaa</td>
  </tr>
  <tr>
    <td >bbbb</td>
  </tr>
</table>
 <script type="text/javascript"> 
 $(document).ready(function(){
    //jQuery ready is quicker than onload
   $(".stripeMe tr").mouseover(function()          {$(this).removeClass("over");$(this).addClass("over");}).mouseout(function()  {$(this).removeClass("over");});
  $(".stripeMe tr:even").addClass("alt");
 });
</script>
</body>
</html>

Upvotes: 0

DanielB
DanielB

Reputation: 20240

You over style is overridden with your alt style. You have to switch the lines.

#table tr.alt td {background: #ecf6fc;}
#table tr.over td{background: #bcd4ec;}

Now .alt has a lower priority than .over because it's defined earlier.

Upvotes: 2

yoavmatchulsky
yoavmatchulsky

Reputation: 2960

change the CSS:

#table tr td { /* regular not hovered */ }
#table tr.alt td { /* alternative, not hovered */ }

#table tr.over td {background: #bcd4ec;}
#table tr.alt.over td {background: #ecf6fc;}

Upvotes: 0

Related Questions