i trying add active class nav item, depending page on. using script:
<script type="text/javascript"> $(document).ready(function () { $("#side-bar a").click(function () { var id = $(this); $(id).siblings().find(".active").removeclass("active"); $(id).addclass("active"); localstorage.setitem("selectedolditem", id); }); var selectedolditem = localstorage.getitem('selectedolditem'); if (selectedolditem !== null) { $(selectedolditem).siblings().find(".active").removeclass("active"); $(selectedolditem).addclass("active"); } }); </script>
see full jsfiddle here: https://jsfiddle.net/ebo7hlo9/ adds active class, loads new page, disappears. doing wrong?
https://jsfiddle.net/ebo7hlo9/10/ - here's fiddle!
$(document).ready(function () { $("#side-bar a").click(function () { var id = $(this); $(".active").removeclass("active"); $(id).addclass("active"); localstorage.setitem("selectedolditem", $(id).text()); }); var selectedolditem = localstorage.getitem('selectedolditem'); if (selectedolditem !== null) { $("a:contains('" + selectedolditem + "')").addclass("active"); } });
your code having issues remembering element grab. think it's due web storage api's unfamiliarity objects. instead got text element selected, stored in localstorage , on page load matched correct element. there part of code dealing finding class "active" within siblings()
of selected element , removing it. complex of code largely unnecessary. replaced class selector $(".active")
i didn't change in code, i'd advise against using localstorage
in favor of sessionstorage
storage clear on tab/browser close.
for more info take @ previous stackoverflow post: storing objects in html5 localstorage