March 10, 2012
How can I consolidate this jquery code
Question by user1261582
I have navigation elements that add a class to the clicked link, and removes the class from the remaining links. How can I consolidate this easily into one function that recognizes which link is clicked and removes the class from the remaining links (or active link)
Heres code for one link – trying to avoid this for each link:
$("#work").click(function () {
$(this).addClass('active');
$("#about").removeClass('active');
$("#testimonial").removeClass('active');
$("#instruction").removeClass('active');
$("#blog").removeClass('active');
$("#contact").removeClass('active');
});
Thanks
Answer by James Aylett
I may be misunderstanding the question, but how about:
function mark_active() {
$('a').removeClass('active');
$(this).addClass('active');
}
$("#work, #about, #testimonial, #instruction, #blog, #contact").click(mark_active);
Answer by Starx
Considering, all the links are <a>
and inside a parent lets say #menu
.
var allchild = $("#menu").children("a");
allchild.click(function () {
allchild.removeClass('active'); //remove the classes from all the menus
$(this).addClass('active');
});
Even if not
$("#work").click(function () {
$("#work, #about, #testimonial, #instruction, #blog, #contact").removeClass('active');
$(this).addClass('active');
});