0

i got this script to add to some "li"'s the class "activeyo" when someone clicks it.The links realod the same page , but after the page is reloaded the added class is gone. I readed this: https://developer.mozilla.org/en-US/docs/DOM/Storage and this Remembering jQuery tab position after page reloads

But i cant understand how to properly use the local storage so i can css properly the li's even after the reload.

$(document).ready(function() {
$('#alpha_ul li a ').click(function() {
$('#alpha_ul li a ').removeClass("activeyo");
$(this).addClass("activeyo");
});               
});

Tried code:

function yo(alpha) {
$('#alpha_ul li a ').removeClass("activeyo");
alpha.addClass("activeyo");

}          
$("#alpha_ul li a").click(function () {
            if (localStorage) localStorage['alpha'] = $(this).closest('li').index();
            yo($(this));
        });      

});

The above code does exactly what the first block of code does. after refresh the class is removed.

Community
  • 1
  • 1
IseNgaRt
  • 601
  • 1
  • 4
  • 22
  • Have you even tried it? – Shomz Dec 23 '14 at 13:50
  • did you try using local storage – Prabhu Murthy Dec 23 '14 at 13:52
  • tried this: $("a #alpha_ul").click(function () { if (localStorage) localStorage['#alpha_ul'] = $(this).closest('li').index(); activate($(this)); }); – IseNgaRt Dec 23 '14 at 13:52
  • Its pretty straight-forward. Save something with localStorage.yourVariableName = 'yourValue'; and check if value is set with if(typeof localStorage.yourVariableName !== 'undefined') – trainoasis Dec 23 '14 at 13:53
  • possible duplicate of [Storing Objects in HTML5 localStorage](http://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage) – Jonathan Dec 23 '14 at 13:53

2 Answers2

0
localStorage.someProp = 'azaza'; // you can add someting to it
localStorage.removeItem('someProp'); // and you can remove something.

And that's it. Not sure how do CSS classes relate to the question. localStorage is global. localStorage's state is saved through page reloads. So basically if you do

localStorage.someProp = 'azaza';

and then reload the page you will still have an access to that data by

var someValue = localStorage.someProp;

Then you can do whatever you want with that value.

0

You were so close with your example, the thing you forgot to do is to set the class from the local storage on page load:

function yo(alpha) {
    $('#alpha_ul li a ').removeClass("activeyo");
    alpha.addClass("activeyo");
}          

$("#alpha_ul li a").click(function () {
            if (localStorage) localStorage['alpha'] = $(this).closest('li').index();
            yo($(this));
        });      
});

// this is what you need
if (localStorage && localStorage.alpha) {
    yo( $("#alpha_ul li").eq(localStorage.alpha) );
}
Shomz
  • 37,421
  • 4
  • 57
  • 85