>> JSFIDDLE <<
var imgFilterBtn = $("nav > ul > li > ul > li > a");
$("img").fadeIn("slow");
imgFilterBtn.click(function() {
var fadeInClass = $(this).attr("id");
var wrongFilter = $(this).parent("li").parent("ul").children("li").children("a");
wrongFilter.removeClass(); // un-style all links in one sub-list
$(this).toggleClass("selected"); // style selected link
var wrongFilterID = wrongFilter.attr("id");
$("#imgWrap").removeClass(wrongFilterID); // remove all classes from imgWrap that are equal to an ID all LI-items in the current list
$("#imgWrap").toggleClass(fadeInClass); // toggle the class that is equal to the ID of the clicked a-element
$("img").hide(); // hide all images
var imgWrapClass = $("#imgWrap").attr("class");
$("#imgWrap").children("img." + imgWrapClass).fadeIn("fast"); // fade in all elements that have the same class as imgWrap
});
I have done my best to include comments that explain what the script is doing.
1. What works:
- The images fade in on document load
- The “selected” class is toggled (but not toggled BACK!)
- The class on
#imgWrapis toggled, but doesn’t get toggled back - Images are hidden and show when a list-item (actually its parent
li) is clicked
2. What does not work
- When a li-item is clicked, the other classes don’t get deleted
- Things mentioned above
3. What should happen
When a user clicks a link, the ID of that linked is passed on to a class which is assigned to #imgWrap. But before this class is assigned, all other classes that are the same as the ID’s of other list items of THE SAME LIST (so not of another list) get deleted. So, when you click black and fashion, and then brown #imgWrap should have the classes fashion and brown, and black should have been deleted.
I am guessing I am missing an each function but I’m not sure.
The problem seems to be that
wrongFiltercontains allaelements of that particular list andwrongFilter.attr("id")will always select the ID of the first selected element.Regarding the toggling: If you select the element that is already selected, you first remove the
selectedclass and then add it again. Similar to the class added to#imgWrap.Restrict the selection to the actual selected element and fix the class adding/removal:
But now it can be that
wrongFilterIDisundefinedand the next call toremoveClasswould remove all classes form#imgWrap. So you have to add a test:Another problem is that
imgWrapClasscan be a space delimited string of classes, e.g."fashion black", which means thatwill result in
which is not what you want.
You have to create a proper selector from that string, e.g.:
With all that fixed, it seems to work properly:
DEMO