I have weird behavior using jQuery Click-Function. I also tried this with on-EventHandler. There is some simple markup from Twitter Bootstrap Navbar, and I'm trying to change the li-tag CSS class. In this case, I want to remove the active CSS class and add it to the current li-tag. But the change is applied with a one-click shift. Therefore, when, for example, “Preview” is the current visually active element, and I click on “Document”, the CSS class does not seem to change. When I click “Slidecast”, then the visual active element is “Document”, which is not the expected behavior. Next Click "Preview", and now "Slidecast" is a visual active element. What am I doing wrong? I tried it with delete and add, as well as with toggleClass, but that doesn't matter. Here is my code and markup. JS wrapped in Dom-Ready-Function.
<div class="navbar"> <div class="navbar-inner"> <ul class="nav"> <li class="active"><a href="#!document_defaultview">Document</a></li> <li><a href="#!document_slidecast">Slidecast</a></li> <li><a href="#!document_preview">Preview</a></li> <li><a href="#!document_notes">Notes</a></li> <li><a href="#!document_questions">Questions</a></li> <li><a href="#!document_activities">Activities</a></li> </ul> </div> </div>
Js
$("#document_navbar a").on('click', function(e) { // Hide all content, display the one related to hash-tag $(".document_view").toggle(false); $(app_locationToId($(this).attr("href"))).toggle(true); // Here is the part that does not work: //$("#document_navbar li.active").removeClass("active"); //$("a[href='" + window.location.hash + "']").parent().addClass('active'); // Another try ... same result as described above! $("#document_navbar li.active").toggleClass("active", false); $("a[href='" + window.location.hash + "']").parent().toggleClass("active", true); });
OK, according to your answers, here is the code I used to solve this problem:
$("#document_navbar a").on('click', function(e) { new_location = app_locationToId($(this).attr("href")); // Hide all content, display the one related to hash-tag $(".document_view").toggle(false); $(new_location).toggle(true); // Change visual active li-tag $("#document_navbar li.active").toggleClass("active", false); $("a[href='" + app_IdToLocation(new_location) + "']").parent().toggleClass("active", true); });
Micha source share