views:

190

answers:

3

I use the following jquery statements,

$(".resultsdiv:odd").css("background-color", "#fff");
$(".resultsdiv:even").css("background-color", "#EFF1F1");
$('.resultsdiv').hover(function() {
      $(this).css('background-color', '#f4f2f2');
   },
   function() {
      $(this).css('background-color', '#fff');
});

Alternate seems to be ok initially but after hover over a div element it doesn't work ... Any suggestion...

+3  A: 

My suggestion is don't manipulate style directly, use classes. So CSS:

.resultsdiv { background-color: #FFF; }
.resultseven { background-color: #EFF1f1; }
.resultshover { background-color: #F4F2F2; }

with:

$(".resultsdiv:even").addClass("resultseven");
$(".resultsdiv").hover(function() {
  $(this).addClass("resultshover");
}, function() {
  $(this).removeClass("resultshover");
});

The problem with a call like:

$(this).css("background", "#FFF");

is that you have no way of knowing how to reset the element to its original state because its original colour may have also been set as inline style, as is the case in your code sample. Classes just make this kind of problem much much easier.

cletus
@Cletus how to add class names to these
Pandiya Chendur
$('#element').addClass('ClassName');
Fermin
@cletus that worked...
Pandiya Chendur
A: 

When you mouse out you set the color of the row to #fff, this will look fine for odd rows but not even.

On mouseout you'll need to check if it's odd or even and set the color accordingly.

Fermin
@Fermin how to do that?
Pandiya Chendur
+1  A: 
<style type="text/css">
  .resultsdiv.odd { background-color: #fff }
  .resultsdiv.even { background-color: #EFF1F1 }
  .resultsdiv.highlight { background-color: #f4f2f2 }
</style>

<script type="text/javascript">
$(function(){
    $(".resultsdiv:odd").addClass('odd');
    $(".resultsdiv:even").addClass('even');
    $('.resultsdiv').hover(function() {
          $(this).addClass('highlight');
       },
       function() {
          $(this).removeClass('highlight');
    });
});
</script>
Mario Menger