Skip to main content
1 of 3
DarkMouse
  • 123
  • 1
  • 1
  • 4

Drying up potentially duplicate JQuery code

I created a fiddle here

http://jsfiddle.net/Mahesha999/CpnYW/1/

Here is my jquery code

$(document).ready(function() {
    $(".nav > li:first-child").click(function(){
      $(this).addClass("highlighted");
      $(".nav > li:nth-child(2), .nav > li:nth-child(3), .nav > li:last-child").removeClass("highlighted");
    });
    $(".nav > li:nth-child(2)").click(function(){
        $(this).addClass("highlighted");
        $(".nav > li:first-child, .nav > li:nth-child(3), .nav > li:last-child").removeClass("highlighted");
    });
    $(".nav > li:nth-child(3)").click(function(){
        $(this).addClass("highlighted");
        $(".nav > li:first-child, .nav > li:nth-child(2), .nav > li:last-child").removeClass("highlighted");
    });
    $(".nav > li:last-child").click(function(){
        $(this).addClass("highlighted");
        $(".nav > li:first-child, .nav > li:nth-child(2), .nav > li:nth-child(3)").removeClass("highlighted");
    });
});

What I'm trying to do is to change the background color when a link is clicked(in this case a list item. When it is no longer clicked, it should revert back to its normal color.

I was able to get this to work via the jquery addClass and removeClass methods, but this seems to be hardcoding it.

DarkMouse
  • 123
  • 1
  • 1
  • 4