I've got an issue with the keeping style value when coming back to a page from another.
I've got a code in jQuery that is showing my menu.
$( "#burger" ).click(function() {
if ($("#burger").hasClass("closed")) {
$( "#menu" ).animate({
marginLeft: "-400px"
}, 600, function() {
$("#burger").removeClass("closed");
$("#burger").addClass("open");
});
} else {
$( "#menu" ).animate({
marginLeft: 0
}, 600, function() {
$("#burger").removeClass("open");
$("#burger").addClass("closed");
});
}
});
And now when i enter other link: for example "gallery.html" and then go back to the "index.html" the menu is no longer there.
How can i keep the margin-left:-400px; in the memory, so when i go back the menu will still be there?
Also i don't wanna to menu will be open everytime i go back, cause in some cases it will be closed and it should remain - so in that case the value should be remembered as "margin-left:0px;"
Thanks for answers!
What's going on is that JQuery or any JS based language works on the client, so when you reload the page or your app cause a Postback every change the JQuery had done will be erased. As posted by zfrisch the best method is to "save" that the user has already clicked on the item and base it's position on whether or not has been changed.
//if you are interested on keeping it this way until browser is erased manually
localStorage.itemClicked = true;
//if the configuration is going to be reset on everytime the user opens his browser
sessionStorage.itemClicked = true;
and in the .ready function you change its position
$(function(){
if(localStorage.itemClicked){
$('#burger').addClass("open");
$('#burger').css({margin-left:"-400px"});
}
});
and your click event should look like this
$( "#burger" ).click(function() {
if ($("#burger").hasClass("closed")) {
$( "#menu" ).animate({
marginLeft: "-400px"
}, 600, function() {
$("#burger").removeClass("closed");
$("#burger").addClass("open");
//save that was clicked
localStorage.itemClicked = true;
});
} else {
$( "#menu" ).animate({
marginLeft: 0
}, 600, function() {
$("#burger").removeClass("open");
$("#burger").addClass("closed");
//remove the key so it is not wasting memory
localStorage.removeItem("itemClicked");
});
}
});
Hope it helped