programmerist programmerist - 6 months ago 34
Javascript Question

how to make <li> add css class active after refreshing page?

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);

});
});



Answer

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");
    }
});