Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Jesus Mendoza
Jesus Mendoza
23,274 Points

Is 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
Colin Bell
29,679 Points

What 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");
});

codepen

Jesus Mendoza
Jesus Mendoza
23,274 Points

Wow that is really good, thanks mate!

Edwin Vergara
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
Jesus Mendoza
23,274 Points

I don't think I can pick 2 best answers right? I didn't know you can add multiple ids. Thanks!