Domanda

I am using one page navigation and I don't know how to remove the active state from the li element when I am in that particular section of the page. I have tried using JQuery and CSS and none works for me (from the console it works obviously).

This is what works in the console:

$('.nav li').removeClass('active');

And in CSS I tried:

.nav > li {  
   background: transparent;
}

I prefer a JQuery solution as it would be easier just to get rid of the active class instead of styling the element.

È stato utile?

Soluzione

Looks like there are multiple listeners for document ready. And your code is getting executed before other handler/handlers which sets the class active again. You can use e.stopImmediatePropagation() to prevent that. Try this:

$(document).ready(function(e){
   e.stopImmediatePropagation();
   $('.nav li').removeClass('active');//or $('.active').removeClass('active');
});

Update:

You can also achieve this using setInterval():

setInterval(function(){
  $('.active').removeClass('active');//remove class active
},1000);

Altri suggerimenti

In your html just don't have the active class on any li when the page loads - Unless you want to have 'home' or something active by default then of course have the active class on the relevant li.

Then when a user clicks on an li try this:

$(".nav li").click(function() {
    $(".nav li").removeClass('active');
    $(this).addClass('active');    
});

The above will remove the active class from whatever li it is on then add it to the one which has been clicked.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top