Reputation: 2966
after clicking li
item. i set active
attribute to css class but li
has a link to forward another page. active css disappear? how to do this? i have been used localstorage to cache my old selected li item. i can not find any solution. How to make alive active class setting after refreshing? how to set active class alive after refreshing page?
<script type="text/javascript">
$(document).ready(function () {
$("li").click(function () {
var id = $(this).attr("id");
console.log(id);
var selectedolditem = localStorage.getItem('selectedolditem');
if (selectedolditem != null) {
$('#' + selectedolditem).siblings().find("active").removeClass("active");
$('#' + selectedolditem).addClass("active");
localStorage.clear();
return;
}
$('#'+id).siblings().find("active").removeClass("active");
$('#' + id).addClass("active");
localStorage.setItem("selectedolditem", id);
});
});
Upvotes: 2
Views: 12309
Reputation: 282
Try following.
$(document).ready(function() {
$('.active').removeClass('active');
var currurl = window.location.pathname;
var val=$('li:has(a[href="'+currurl+'"])').addClass('active');
});
Upvotes: 1
Reputation: 1283
Try following.
$('li').each(function(){
if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
{
$(this).addClass('active').siblings().removeClass('active');
}
});
Upvotes: 9
Reputation: 64526
The problem with your code is you are trying to retrieve it onclick. That's the wrong logic. The correct logic is: when the page loads, retrieve it. When the li
is clicked, store it. You also have a problem when using find("active")
, you need to use the class character .
otherwise it will search for elements with the tag name active
not the class.
$(document).ready(function () {
$("li").click(function () {
var id = $(this).attr("id");
$('#' + id).siblings().find(".active").removeClass("active");
// ^ you forgot this
$('#' + id).addClass("active");
localStorage.setItem("selectedolditem", id);
});
var selectedolditem = localStorage.getItem('selectedolditem');
if (selectedolditem != null) {
$('#' + selectedolditem).siblings().find(".active").removeClass("active");
// ^ you forgot this
$('#' + selectedolditem).addClass("active");
}
});
Upvotes: 11