Tuesday, September 17, 2013

Change list-style onclick with JavaScript

Change list-style onclick with JavaScript

I'm trying to change the style of a list element on click to have a black
background with white text. When I click another one, I want it to return
to its base state of a white background and black text. The problem I'm
having is when I click the second list element, the first one retains the
style generated in the JS. This is not what I want.
Here's the HTML:
<ul class="menu">
<li>
<a href="#">Item One</a>
</li>
<li>
<a href="#">Item Two</a>
</li>
</ul>
And here's the JS
$('.menu > li > a').click(function(){
$(this).css({
'background-color': 'black',
'color': 'white'
});
$(this).siblings('.menu > li > a').css({
'background-color': 'white',
'color':'black'
});
});
I know I'm probably just targeting the wrong thing and I've tried multiple
ways, but I can't seem to figure it out. I think I have the parent,
children, and sibling tree mixed up too. Any help is greatly appreciated!
Here it is on JSFiddle

No comments:

Post a Comment