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?
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With