0

My JavaScript:

$(document).ready(function(){
    $("ul.menu li a").click(function(e){
        $("a").removeClass("selected");
        $(this).addClass("selected");
    });
});

HTML:

<div>                   
    <ul id="top_bookmarks" class="menu list-inline">
        <li><a class="selected" href="/56">item 1</a></li>
        <li><a class="" href="/64">item 2</a></li>
    </ul>
</div>

It works, but when i click on item 2 class "selected" is added only for one second and then it's removed and added back to item 1.

How i can fix it?

Sampson
  • 265,109
  • 74
  • 539
  • 565
user3140714
  • 85
  • 1
  • 9

1 Answers1

1

When you click on the second li -> anchor tag, then check the url. The data is sent via the url and the page reloads and hence resets the page and hence your class.

If you want to stop the page reload, and want to stay on the same page, then you can use event.preventDefaul() method on the click of the anchor. In your case it would be e.preventDefault();

Abhishek Prakash
  • 964
  • 2
  • 10
  • 24
  • Thank you for your reply. However when i use preventDefault() it works fine but a href doesnt work. How i can keep added classes after page reload? – user3140714 Mar 23 '14 at 18:02
  • preventDefault will prevent the default action. What you intend to achieve? – Abhishek Prakash Mar 23 '14 at 18:03
  • Let's say i have two a href's Item 1 and Item 2. I want to highlight currently clicked a href with "selected" CSS class after page reloads. Example: http://i.imgur.com/vWmlScZ.png – user3140714 Mar 23 '14 at 18:08
  • after page reloads? This means you want to navigate to some different page where you have the same dom elements -> div and then add the class to the selected item? – Abhishek Prakash Mar 23 '14 at 18:12
  • Nevermind, i used this http://stackoverflow.com/questions/18999501/bootstrap-3-keep-selected-tab-on-page-refresh Thanks anyway! – user3140714 Mar 23 '14 at 18:29