Reputation: 124
I've got a navigation bar made of icons that change ("light up") when clicked, to indicate which div is currently being shown.
The problem is, I'd like it so when one image is changed (lit up when clicked), all the others revert to their original state.
Currently they are all just simple toggles, which means when I click one and then another, they both stay lit up, which I obviously do not want.
Is there a simple way to implement this?
Edit: I'm currently using this method of jQuery image toggling. I'm a real amateur so I don't know where I'd begin using each toggle to also toggle all of the other icons back to their original state.
Upvotes: 0
Views: 479
Reputation: 91487
Define a class to indicate the selected tab and use CSS to apply the highlight (show/hide an image, change background position of a sprite, whatever). Then:
$("#menu li").click(function (e) {
$("#menu li.selected").removeClass("selected");
$(this).addClass("selected");
});
Edit: To adapt your existing code to use CSS to apply the highlight, change your html so that each menu item has two images:
<ul id="menu">
<li>
<img class="off" src="menu1-original-icon.png" />
<img class="on" src="menu1-lit-up-icon.png" />
</li>
<li>
<img class="off" src="menu2-original-icon.png" />
<img class="on" src="menu2-lit-up-icon.png" />
</li>
...
</ul>
Then, use CSS to hide one and show the other:
#menu .on, #menu .selected .off
{
display: none;
}
#menu .selected .on
{
display: inline;
}
Here's a demo: jsfiddle.net/PLRfJ
To allow selecting none (click on selected deselects it), use .toggleClass()
instead of .addClass()
and exclude this
when removing the class:
$("#menu li").click(function (e) {
$("#menu li.selected").not(this).removeClass("selected");
$(this).toggleClass("selected");
});
Upvotes: 1