1
$(document).ready(function() {

  var $listItems = $('ul li');
  listItems.click(function() {
  $listItems.removeClass('selected'); 
  $(this).addClass('selected');

  });
});

.selected{
   background color: "green";
}

//HTML

           <ul class="nav navbar-nav navbar-right">
                <li class="selected"><a href="index.php">Home</a></li>
                <li><a href="about-us.php">About Us</a></li>
                <li><a href="services.php">Services</a></li>
                <li><a href="portfolio.php">Portfolio</a></li>
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Pages <i class="icon-angle-down"></i></a>
                    <ul class="dropdown-menu">
                        <li><a href="career.php">Career</a></li>
                        <li><a href="blog-item.php">Blog Single</a></li>
                        <li><a href="pricing.php">Pricing</a></li>
                        <li><a href="404.php">404</a></li>
                        <li><a href="registration.php">Registration</a></li>
                        <li class="divider"></li>
                        <li><a href="privacy.php">Privacy Policy</a></li>
                        <li><a href="terms.php">Terms of Use</a></li>
                    </ul>
                </li>
                <li><a href="blog.php">Blog</a></li> 
                <li><a href="contact-us.php">Contact</a></li>
            </ul>

Class gets added for a second and than gets removed to as its default .

mTorres
  • 3,590
  • 2
  • 25
  • 36
Param sohi
  • 121
  • 9
  • 1
    your code looks okay, can you provide a fiddle to show the problem? I guess there's some other component causing trouble, are there any other eventhandlers on these elements? – GNi33 Aug 27 '14 at 12:18
  • 1
    Well .... except for the undefined variable `listItems` .... did you mean `$listItems`? – PeterKA Aug 27 '14 at 12:20
  • I'd suggest it's likely to be event-propagation, clicking on the inner-`
  • ` elements allowing the `click` event to propagate to the parent `
  • `.
  • – David Thomas Aug 27 '14 at 12:21
  • Variable $listItems is not a problem i just removed $ sign while posting question mistakenly .. – Param sohi Aug 27 '14 at 12:23
  • after $(this).addClass('selected'); if I add return false It works but it doesnt go to the page url which is in href. – Param sohi Aug 27 '14 at 12:24
  • This your menu for all pages and you redirects on click links(li). So to get the li selected you have to pass #value in each link and to make a script to check the link hash value to set selected class. – rahul Aug 27 '14 at 12:27
  • Aside what folks have said about `$listItem` and `background-color` you must also remove the quotes from `"green"`. – Jay Blanchard Aug 27 '14 at 12:30