Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJesus Mendoza
23,288 PointsIs there any better way to do this?
I was practicing some jQuery and I was wondering if there is an easiest or better way to do this because I feel the it's too repetitive
$("#navbar li").click(function(){
var anchorID = $(this).children("a").attr("href");
if (anchorID == "#home") {
$(anchorID).removeClass("back").addClass("front");
$("#about").removeClass("front").addClass("back");
$("#contact").removeClass("front").addClass("back");
} else if (anchorID == "#about") {
$("#home").removeClass("front").addClass("back");
$(anchorID).removeClass("back").addClass("front");
$("#contact").removeClass("front").addClass("back");
} else if (anchorID == "#contact") {
$("#home").removeClass("front").addClass("back");
$("#about").removeClass("front").addClass("back");
$(anchorID).removeClass("back").addClass("front");
}
});
Here is the codepen for a live version of it http://codepen.io/Jesusz0r/pen/LEJYBV
2 Answers
Colin Bell
29,679 PointsWhat about if you add a common class to all the sections in the HTML markup? I added one called section, then wrote this:
$("#navbar").on("click", "a", function(){
var $this = $(this);
var anchorID = $($this.attr("href"));
var section = $('.section');
section.removeClass("front").addClass("back");
anchorID.removeClass("back").addClass("front");
});
Edwin Vergara
6,477 Points$("#navbar li").click(function(){
var anchorID = $(this).children("a").attr("href");
$("#home, #about, #contact").removeClass("front").addClass("back");
$(anchorID).removeClass("back").addClass("front");
});
Jesus Mendoza
23,288 PointsI don't think I can pick 2 best answers right? I didn't know you can add multiple ids. Thanks!
Jesus Mendoza
23,288 PointsJesus Mendoza
23,288 PointsWow that is really good, thanks mate!