How can I create different classes on my links so they can show different images when you click on them?
The idea is that the links has its own color and when it is active there must be a little arrow with the same color.
This is what I have so far:
HTML:
<ul>
<li class="red"><a href="#">Link one</a></li>
<li class="blue"><a href="#">Link two</a></li>
</ul>
CSS:
.red {background-color:#f00; }
.red_bnt { background-image:url(image/red_bnt_pil.png); }
.blue {background-color:#00f; }
.blue_bnt { background-image:url(image/red_bnt_pil.png); }
jQuery:
<script type="application/x-javascript">
$('.red').click(function(){
$('.red').removeClass('red_bnt');
$(this).addClass('red_bnt');
});
</script>
And then repeat it for the blue as well.
But it is not working …
what am I doing wrong?
Your jQuery is saying that when an element with the class “red” is clicked, remove class “red_bnt” from all elements with the “red” class and then add red_bnt to the clicked element. Since the blue button doesn’t have the class red, it never even enters the equation. Instead, add a common class to the buttons and then a use a common class name, such as “active”, which would activate the background CSS.
I’d change your CSS to:
The HTML to:
and the jQuery to:
Here’s a jsFiddle for it: http://jsfiddle.net/FS4Du/. I used the colors darkred and dodgerblue in place of your images.
Note: I used the hover class instead of just reusing active to avoid having to handle the case where the element that was clicked on (the active element) is then hovered over.