Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hover effect jQuery

Tags:

jquery

I have a bunch of li elements that I want to alternate in color using odds and evens, and then highlight based on mouse hover. In order to un-highlight I need to keep track of what the color used to be, odd or even. To do this when I apply the highlight color, I first set an arbitrary attribute to it. Are there any downsides to doing it this way? Is there a better way? Here's the code:

<script type="text/javascript">
var init = function(event){
$("li:odd").css({'background-color' :  '#eeeeee', 'font-weight' : 'bold'});
$("li:even").css('background-color', '#cccccc');  
    //initial colors setup

    $("li").hover(
    function ()   //hover over
    {
        var current = $(this);
        current.attr('old-background', current.css('background-color'));
        current.css('background-color', '#ffee99');

    }
    , function()  //hover out
{
    var current = $(this);
    current.css('background-color', current.attr('old-background'));
})

}
$(document).ready(init);
</script>

So is there a better way to do this?

like image 805
Ori Avatar asked Feb 28 '23 13:02

Ori


1 Answers

I agreen with benlumley, you should use addClass/removeClass methods.

Your CSS may look like,

li {
    font-weight: bold;
}

li.odd {
    background-color: '#eee';
}

li.even {
    background-color : '#ccc';
}

li.hover {
    background-color : '#ffee99';
}

Your init function will now look like,

var init = function(event)
{
    $('li:odd').addClass('odd');
    $('li:odd').addClass('even');

    $('li').hover(  function()
                    {
                        $(this).addClass('hover');
                    },
                    function()
                    {
                        $(this).removeClass('hover');
                    }
                   );

}

This code has advantage that if you want to change the styling of how those list items look, you can go to your CSS code and change the colors without touching your JS code!

like image 123
SolutionYogi Avatar answered Apr 21 '23 13:04

SolutionYogi