3

So I have a list of divs that have alternating background colors through jQuery. These also have rollovers that change the background color. The problem is, the rollover function only allows me to animate this class back to one background color on mouseout, but like I said before, I have an alternating background color. How can I handle this in jQuery? My code below was my attempt at an if, else statement with even and odd, but I don't know the proper syntax.

$(document).ready(function() {
    $('.whycapad_staff:even').css({"background-color":"#eaebeb"});
    $('.whycapad_staff').hover(function() {
        $(this).stop().animate({"background-color":"#5facf8"}, 300);
    }, function(){
        if ($(this = ':even')){
            $(this).stop().animate({"background-color":"#eaebeb"}, 300)
        };
        else {
                $(this).stop().animate({"background-color":"#FFFFFF"}, 300)
        }
    })
})
TylerH
  • 20,799
  • 66
  • 75
  • 101
A_funs
  • 1,228
  • 2
  • 19
  • 31
  • Why are you using JavaScript to do what can be done with CSS? – Matt Ball Oct 06 '11 at 18:50
  • because the individual divs are dynamically generated and i want to use jQUERY – A_funs Oct 06 '11 at 18:52
  • 1
    @A_funs as long as you use classes, css is just fine ^_^ – Naftali Oct 06 '11 at 18:54
  • Don't downvote. It's not a bad question, it just may not be a good design decision. Instead point him towards a better solution. http://meta.stackexchange.com/questions/33286/downvotes-versus-close-votes-on-questions . On second thought, his use of animations and the fact that :even selector isn't supported by IE8 may mean that this is actually a very good question. – mrtsherman Oct 06 '11 at 18:59

1 Answers1

5

Just use css:

.whycapad_staff:nth-child(even) {
     background-color:#eaebeb;
}
.whycapad_staff:hover {
     background-color:#5facf8;
}

Demo: http://jsfiddle.net/maniator/npWnm/

Here is an example if you just want to use jQuery: http://jsfiddle.net/maniator/npWnm/5/

$(function() { //jQuery fallback
    $('.whycapad_staff').hover(function() {
        $(this).data('b-color', $(this).css('background-color'));
        $(this).css('background-color', '#5facf8');
    }, function() {
        $(this).css('background-color', $(this).data('b-color'));
    });
});

Full fallback: http://jsfiddle.net/maniator/npWnm/9/

$(function() { //jQuery fallback
    $('.whycapad_staff').each(function(index, item){
        if(index%2 == 1){
            $(this).css('background-color', '#eaebeb');
        }
    });
    $('.whycapad_staff').hover(function() {
        $(this).data('b-color', $(this).css('background-color'));
        $(this).css('background-color', '#5facf8');
    }, function() {
        $(this).css('background-color', $(this).data('b-color'));
    });
});
Naftali
  • 144,921
  • 39
  • 244
  • 303