I have this HTML toggle button for my menu:
<a href="#" id="toggle_nav" class="sidebar-toggle" data-toggle="offcanvas" role="button">
How can i save the toggle state to reload it on page load
I have started off with:
$(document).ready(function() {
$("#toggle_nav").toggle(function() {
});
});
but im not sure what to use to keep the state
Like people are saying in the commends you can use html 5 web storage.
You have 2 types:
- localStorage - stores data with no expiration date
- sessionStorage - stores data for one session
how to set:
localStorage.setItem("name", "value");
How to get the value
localStorage.getItem("name");
So now can you do a simple check like:
if (localStorage.getItem("toggle") === null) {
//hide or show menu by default
//do not forget to set a htlm5 cookie
}else{
if(localStorage.getItem("toggle") == "yes"){
//code when menu is visible
}else{
//code when menu is hidden
}
}
More information here
Use a hidden field. Use JS to set this hidden field value whenever the panel is opened or closed, and to check the hidden field on pageload.
Example-
In your JS, I use one function to set which panels are open/closed and a 2nd to arrange them. This example is based on having multiple panels on your page but you can quickly change it to handle just one panel if needed.
function init() {
if ($("#hdnOpenPanels").val()) {
$(".fixPanels").click();
}
}
// Ensures that the correct panels are open on postback
$(".checkPanels").click(function () {
var checkPanel1= $("#Panel1").hasClass("in");
var checkPanel2 = $("#Panel2").hasClass("in");
var checkPanel3 = $("#Panel3").hasClass("in");
$("#hdnOpenPanels").val(checkPanel1 + "|" + checkPanel2 + "|" + checkPanel3);
});
$(".fixPanels").click(function () {
if ($("#hdnOpenPanels").val().split('|')[0] === "true") {
$("#Panel1").collapse('show');
} else {
$("#Panel1").collapse('hide');
}
if ($("#hdnOpenPanels").val().split('|')[1] === "true") {
$("#Panel2").collapse('show');
} else {
$("#Panel2").collapse('hide');
}
if ($("#hdnOpenPanels").val().split('|')[2] === "true") {
$("#Panel3").collapse('show');
} else {
$("#Panel3").collapse('hide');
}
});
Now you have two easy classes available to add to any items that will require the page to know which panels are open (.checkPanels) and also to "fix" which panels should be open (.fixPanels). If you have modals on the page they'll need to "fixPanels" when they closed (even though there may not have been a postback).
On your code-behind:
Add this to your PageLoad:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["sPanels"] != null)
{
hdnOpenPanels.Value = Session["sPanels"].ToString();
Session.Remove("sPanels");
}
if (IsPostBack){...}
else {...}
}
Finally, on any code-behind functions that will be causing a post-back affecting the panels, add this line at the bottom of the function(s):
Session["sPanels"] = hdnOpenPanels.Value;
There are any number of ways to accomplish this, including local storage, cookies, URL parameters, anchor fragments, and server-side storage.
If you need to persist the value for a user, regardless of browser, you'll need to store it on the server side as a user preference against an identified user's profile.
If you need to persist against a single browser instance, regardless of user, you can use a client-side solution like localStorage (for persistence across browser sessions) sessionStorage (for persistence within a single browser session) or cookies (which can be configured to do either).
For example, here is a solution that uses localStorage to persist the state of a toggle across page reloads and browser sessions.
This code does not run in an SO snippet, so see this Fiddle for a demo.
Javascript
var menuStateKey = "menu.toggle_nav.state";
$(document).ready(function() {
var $nav = $("nav");
var setInitialMenuState = function() {
// Note: This retrieves a String, not a Boolean.
var state = localStorage.getItem(menuStateKey) === 'true';
setNavDisplayState(state);
};
var toggleNav = function() {
var state = $nav.is(':visible');
state = !state;
localStorage.setItem(menuStateKey, state);
setNavDisplayState(state);
};
var setNavDisplayState = function(state) {
if (state) {
$nav.show();
} else {
$nav.hide();
}
};
$("#toggle_nav").click(toggleNav);
setInitialMenuState();
});
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>I am the nav</nav>
Toggle
You can extent toggle
$.prototype._toggle = $.prototype.toggle;
$.prototype.toggle = function() {
// save to localStorage
$.prototype._toggle.call(this)
}
And write code that use localStorage to start toggle
You can store toggle state in localStorage object.
// Check browser support
if (typeof(Storage) != "undefined") {
// Store
localStorage.setItem("toggleState", value);
// Retrieve
localStorage.getItem("toggleState");
} else {
"Sorry, your browser does not support Web Storage...";
}
Check out Local Storage - Dive Into HTML5
There are JQuery plugins available to facilitate this.
$.localStorage;
storage=$.localStorage;
storage.set('foo','value');
storage.get('foo');
Read more at Jquery Storage API.
Cheers !
As others explained we can use localStorage(HTML5) or else we can use cookies
Please refer this article on how to persist the data using cookies.
As this implementation requires less data to be stored in cookie. Using cookie would be the good approach for your implementation.
I have one html page 1.html and i want to get some text content and store it to a js.js file using jquery to get the text by id.
This code only works in 1.html page, where the text I want to copy from is but not in 2.html file.
Here is my code. Note that it works if I store text inside localstorage setter second parameter.
$( document ).ready(function() {
var c1Title= $('#r1c1Title').text();
//changing c1Title to any String content like "test" will work
localStorage.setItem("t1",c1Title);
var result = localStorage.getItem("t1");
$("#title1").html(result);
alert(result);
});
Here is the complete demo I am working on Github:
You need to use either localStorage or cookies.
With localStorage
On the first page, use the following code:
localStorage.setItem("variableName", "variableContent")
That sets a localStorage variable of variableName for the domain, with the content variableContent. You can change these names and values to whatever you want, they are just used as an example
On the second page, get the value using the following code:
localStorage.getItem("variableName")
That will return the value stored in variableName, which is variableContent.
Notes
There is a 5MB limit on the amount of data you can store in localStorage.
You can remove items using localStorage.removeItem("variableName").
Depending on where you are, you may need to take a look at the cookie policy (this effects all forms of websites storing data on a computer, not just cookies). This is important, as otherwise using any of these solutions may be illegal.
If you only want to store data until the user closes their browser, you can use sessionStorage instead (just change localStorage to sessionStorage in all instances of your code)
If you want to be able to use the variable value on the server as well, use cookies instead - check out cookies on MDN
For more information on localStorage, check out this article on MDN, or this one on W3Schools
Please try to use this code. It's better to use local storage.
Here you need to make sure that you are setting this local storage
value in parent html page or parent js file.
create local storage
localStorage.setItem("{itemlable}", {itemvalue});
localStorage.setItem("variable1", $('#r1c1Title').text());
localStorage.setItem("variable2", $('#r1c2Title').text());
Get local storage value
localStorage.getItem("{itemlable}")
alert(localStorage.getItem("variable1") + ' Second variable ::: '+ localStorage.getItem("variable2"));
For more information follow this link https://www.w3schools.com/html/html5_webstorage.asp
If you wanted to store in div then follow this code.
Html Code
<div class="div_data"></div>
Js code:
$(document).ready(function () {
localStorage.setItem("variable1", "Value 1");
localStorage.setItem("variable2", "Value 2");
$(".div_data").html(' First variable ::: '+localStorage.getItem("variable1") + ' Second variable ::: '+ localStorage.getItem("variable2"));
});
Hope this helps.
You can use local storage as mentioned in above comments. Please find below how to write in javascript.
Local Storage Pros and Cons
Pros:
Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity.
5120KB (5MB which equals 2.5 Million chars on Chrome) is the default storage size for an entire domain.
This gives you considerably more space to work with than a typical 4KB cookie.
The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.
The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.
Cons:
It works on same-origin policy. So, data stored will only be available on the same origin.
// Store value in local storage
localStorage.setItem("c1Title", $('#r1c1Title').text());
// Retrieve value in local storage
localStorage.getItem("c1Title");
Your html div
<div id="output"></div>
Add Javascript Code
$('#output').html(localStorage.getItem("c1Title"));
Let me know if it not works
Create a common.js file and modified this and save.
Session = (function () {
var instance;
function init() {
var sessionIdKey = "UserLoggedIn";
return {
// Public methods and variables.
set: function (sessionData) {
window.localStorage.setItem(sessionIdKey, JSON.stringify(sessionData));
return true;
},
get: function () {
var result = null;
try {
result = JSON.parse(window.localStorage.getItem(sessionIdKey));
} catch (e) { }
return result;
}
};
};
return {
getInstance: function () {
if (!instance) {
instance = init();
}
return instance;
}
};
}());
function isSessionActive() {
var session = Session.getInstance().get();
if (session != null) {
return true;
}
else {
return false;
}
}
function clearSession() {
window.localStorage.clear();
window.localStorage.removeItem("CampolUserLoggedIn");
window.location.assign("/Account/Login.aspx");
}
Insert like this.
$(function () {
if (!isSessionActive()) {
var obj = {};
obj.ID = 1;
obj.Name = "Neeraj Pathak";
obj.OrganizationID = 1;
obj.Email = "npathak56#gmail.com";
Session.getInstance().set(obj);
}
///clearSession();
});
get like this way
LoggedinUserDetails = Session.getInstance().get();
I want to have a boolean variable to retain its value even if the Page reloads in Jquery. Here is what I am doing.
var TimedOut = false;
alert("Time Out Value = " + TimedOut);
if (!TimedOut) {
//do some Processing and stay on same Page
Timedout = true;
// redirect to current Page using window.location.href on session timeout
}
The Value of Timedout which I am setting it in the loop is always false, and if statement is always true. I want it to load only once for false and once set to true it should retain the value. I am using this to decide if we need to redirect to home page or not.
Not sure if I can do this via JQuery.
try to use a cookie this library could do the trick, https://github.com/js-cookie/js-cookie
Cookies.set('timeout', 'false');
var timeout = Cookies.get('timeout');
alert("Time Out Value = " + TimedOut);
if (!TimedOut) {
//do some Processing and stay on same Page
Cookies.set('timeout', 'true');
// redirect to current Page using window.location.href on session timeout
}
I just replace your code and added the cookie functionality but you know better the logic.
I hope that helps.
You could persist that value in localStorage:
localStorage.setItem('Timedout', true);
and
localStorage.getItem('Timedout');
Yes, you can do this via jQuery with a cookie as jack wrote or WebStorage API (localStorage or sessionStorage) which is for new browsers only with HTML5 support.
It sounds simple and I think it should be simple, but somehow I don't get it to work...
I want to set a Cookie using Javascript and this Cookie should be removed when the user quits the browser. Setting the cookie and getting the value is not the problem. But when I quit the browser and reopen it, the cookie is still there (Firefox).
I use jQuery and the Cookie-Plugin.
Here is my test code:
$(document).ready(function(){
$('#output').append( '<li>initialize...</li>' );
var $cookieVal = $.cookie('testCookie');
$('#output').append( '<li>check cookie...</li>' );
if(!$cookieVal) {
$('#output').append( '<li>set cookie...</li>' );
$.cookie('testCookie', 'eat cookies', { path: '/' });
//console.log( $.cookie() );
} else {
$('#output').append( '<li>cookie is already set...</li>' );
$('#output').append( '<li>cookie value: '+$.cookie('testCookie')+'</li>' );
}
});
Please find the working example at jsFiddle.
I am beginning to wonder if your testing method might be the problem here. So, I am going to write this in a specific way.
Actual Answer: Browser Setting
In Firefox, Options>General>When Firefox starts>"Show my windows and tabs from last time" is going to preserve your previous session. Change this setting to see that this is indeed working as it is supposed to. Firefox is prolonging your session. For further information, see this "bug": http://bugzilla.mozilla.org/show_bug.cgi?id=530594
There are similar settings in most browsers that probably behave the same way.
Original Answer:
I created a fiddle, http://jsfiddle.net/8Ahg2/ that uses document.cookie rather than jquery cookie plugin. Here is how you test this. (source below)
copy the following URL to your clipboard: http://fiddle.jshell.net/8Ahg2/show/
Completely close your browser of choice - this should be browser independent.
Open your browser, paste the url. The first time it should say: check cookie...
set cookie...
Refresh the page, notice that it should now say the value of the cookie ("test")
Close your browser completely again.
Navigate to the URL that should still be in your clipboard. *Do not refresh the page on the first view, it should again say 'check cookie...
set cookie...'
js
$(document).ready(function () {
$('#output').append('<li>initialize...</li>');
//this regex gets the "name" cookie out of the string of cookies that look like this: "name=test;var2=hello;var3=world"
var cookieVal = document.cookie.replace(/(?:(?:^|.*;\s*)name\s*\=\s*([^;]*).*$)|^.*$/, "$1");
$('#output').append('<li>check cookie...</li>');
if (!cookieVal) {
$('#output').append('<li>set cookie...</li>');
document.cookie = "name=test";
} else {
$('#output').append('<li>cookie is already set...</li>');
$('#output').append('<li>cookie value: ' + cookieVal + '</li>');
}
});
There is some code that worked for me. It should expire when you close the browser because of the date to expire being before now:
var vEnd = new Date();
vEnd.setDate(vEnd.getDate() - 1);
var endOfCookieText = "; expires=" + vEnd.toGMTString() + "; path=/";
document.cookie = escape('testCookie') + "=" + escape("eat cookies") + endOfCookieText;
FIDDLE MODIFIED
Note that the fiddle gives a bunch of load errors on the console for me.
My Case: localStorage with key + value that should be deleted when browser is closed and not single tab.
Please see my code if its proper and what can be improved:
//create localStorage key + value if not exist
if (localStorage) {
localStorage.myPageDataArr = {
"name" => "Dan",
"lastname" => "Bonny"
};
}
//when browser closed - psedocode
$(window).unload(function() {
localStorage.myPageDataArr = undefined;
});
should be done like that and not with delete operator:
localStorage.removeItem(key);
Use with window global keyword:-
window.localStorage.removeItem('keyName');
You should use the sessionStorage instead if you want the key to be deleted when the browser close.
You can make use of the beforeunload event in JavaScript.
Using vanilla JavaScript you could do something like:
window.onbeforeunload = function() {
localStorage.removeItem(key);
return '';
};
That will delete the key before the browser window/tab is closed and prompts you to confirm the close window/tab action. I hope that solves your problem.
NOTE: The onbeforeunload method should return a string.
localStorage.removeItem(key); //item
localStorage.clear(); //all items
There is a very specific use case in which any suggestion to use sessionStorage instead of localStorage does not really help.
The use-case would be something as simple as having something stored while you have at least one tab opened, but invalidate it if you close the last tab remaining.
If you need your values to be saved cross-tab and window, sessionStorage does not help you unless you complicate your life with listeners, like I have tried.
In the meantime localStorage would be perfect for this, but it does the job 'too well', since your data will be waiting there even after a restart of the browser.
I ended up using a custom code and logic that takes advantage of both.
I'd rather explain then give code. First store what you need to in localStorage, then also in localStorage create a counter that will contain the number of tabs that you have opened.
This will be increased every time the page loads and decreased every time the page unloads. You can have your pick here of the events to use, I'd suggest 'load' and 'unload'.
At the time you unload, you need to do the cleanup tasks that you'd like to when the counter reaches 0, meaning you're closing the last tab.
Here comes the tricky part: I haven't found a reliable and generic way to tell the difference between a page reload or navigation inside the page and the closing of the tab.
So If the data you store is not something that you can rebuild on load after checking that this is your first tab, then you cannot remove it at every refresh.
Instead you need to store a flag in sessionStorage at every load before increasing the tab counter.
Before storing this value, you can make a check to see if it already has a value and if it doesn't,
this means you're loading into this session for the first time, meaning that you can do the cleanup at load if this value is not set and the counter is 0.
use sessionStorage
The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the browser window.
The following example counts the number of times a user has clicked a button, in the current session:
Example
if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";
Try using
$(window).unload(function(){
localStorage.clear();
});
Hope this works for you
There are five methods to choose from:
setItem(): Add key and value to localStorage
getItem(): Retrieve a value by the key from localStorage
removeItem(): Remove an item by key from localStorage
clear(): Clear all localStorage
key(): Passed a number to retrieve nth key of a localStorage
You can use clear(), this method when invoked clears the entire storage of all records for that domain. It does not receive any parameters.
window.localStorage.clear();
for (let i = 0; i < localStorage.length; i++) {
if (localStorage.key(i).indexOf('the-name-to-delete') > -1) {
arr.push(localStorage.key(i));
}
}
for (let i = 0; i < arr.length; i++) {
localStorage.removeItem(arr[i]);
}
8.5 years in and the original question was never actually answered.
when browser is closed and not single tab.
This basic code snippet will give you the best of both worlds. Storage that persists only as long as the browser session (like sessionStorage), but is also shareable between tabs (localStorage).
It does this purely through localStorage.
function cleanup(){
// place whatever cleanup logic you want here, for example:
// window.localStorage.removeItem('my-item')
}
function tabOpened(){
const tabs = JSON.parse(window.localStorage.getItem('tabs'))
if (tabs === null) {
window.localStorage.setItem('tabs', 1)
} else {
window.localStorage.setItem('tabs', ++tabs)
}
}
function tabClosed(){
const tabs = JSON.parse(window.localStorage.getItem('tabs'))
if (tabs === 1) {
// last tab closed, perform cleanup.
window.localStorage.removeItem('tabs')
cleanup()
} else {
window.localStorage.setItem('tabs', --tabs)
}
}
window.onload = function () {
tabOpened();
}
window.onbeforeunload = function () {
tabClosed();
}
why not used sessionStorage?
"The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the browser window."
http://www.w3schools.com/html/html5_webstorage.asp
Although, some users already answered this question already, I am giving an example of application settings to solve this problem.
I had the same issue. I am using https://github.com/grevory/angular-local-storage module in my angularjs application. If you configure your app as follows, it will save variable in session storage instead of local storage. Therefore, if you close the browser or close the tab, session storage will be removed automatically. You do not need to do anything.
app.config(function (localStorageServiceProvider) {
localStorageServiceProvider
.setPrefix('myApp')
.setStorageType('sessionStorage')
});
Hope it will help.
Here's a simple test to see if you have browser support when working with local storage:
if(typeof(Storage)!=="undefined") {
console.log("localStorage and sessionStorage support!");
console.log("About to save:");
console.log(localStorage);
localStorage["somekey"] = 'hello';
console.log("Key saved:");
console.log(localStorage);
localStorage.removeItem("somekey"); //<--- key deleted here
console.log("key deleted:");
console.log(localStorage);
console.log("DONE ===");
} else {
console.log("Sorry! No web storage support..");
}
It worked for me as expected (I use Google Chrome).
Adapted from: http://www.w3schools.com/html/html5_webstorage.asp.
I don't think the solution presented here is 100% correct because window.onbeforeunload event is called not only when browser/Tab is closed(WHICH IS REQUIRED), but also on all other several events. (WHICH MIGHT NOT BE REQUIRED)
See this link for more information on list of events that can fire window.onbeforeunload:-
http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
After looking at this question 6 years after it was asked, I found that there still is no sufficient answer to this question; which should achieve all of the following:
Clear Local Storage after closing the browser (or all tabs of the domain)
Preserve Local Storage across tabs, if at least one tab remains active
Preserve Local Storage when reloading a single tab
Execute this piece of javascript at the start of each page load in order to achieve the above:
((nm,tm) => {
const
l = localStorage,
s = sessionStorage,
tabid = s.getItem(tm) || (newid => s.setItem(tm, newid) || newid)((Math.random() * 1e8).toFixed()),
update = set => {
let cur = JSON.parse(l.getItem(nm) || '{}');
if (set && typeof cur[tabid] == 'undefined' && !Object.values(cur).reduce((a, b) => a + b, 0)) {
l.clear();
cur = {};
}
cur[tabid] = set;
l.setItem(nm, JSON.stringify(cur));
};
update(1);
window.onbeforeunload = () => update(0);
})('tabs','tabid');
Edit: The basic idea here is the following:
When starting from scratch, the session storage is assigned a random id in a key called tabid
The local storage is then set with a key called tabs containing a object those key tabid is set to 1.
When the tab is unloaded, the local storage's tabs is updated to an object containing tabid set to 0.
If the tab is reloaded, it's first unloaded, and resumed. Since the session storage's key tabid exists, and so does the local storage tabs key with a sub-key of tabid the local storage is not cleared.
When the browser is unloaded, all session storage will be cleared. When resuming the session storage tabid won't exists anymore and a new tabid will be generated. Since the local storage does not have a sub-key for this tabid, nor any other tabid (all session were closed), it's cleared.
Upon a new created tab, a new tabid is generated in session storage, but since at least one tabs[tabid] exists, the local storage is not cleared
This will do the trick for objects.
localStorage.removeItem('key');
Or
localStorage.setItem('key', 0 );
You can simply use sessionStorage. Because sessionStorage allow to clear all key value when browser window will be closed .
See there : SessionStorage- MDN
This is an old question, but it seems none of the answer above are perfect.
In the case you want to store authentication or any sensitive information that are destructed only when the browser is closed, you can rely on sessionStorage and localStorage for cross-tab message passing.
Basically, the idea is:
You bootstrap from no previous tab opened, thus both your localStorage and sessionStorage are empty (if not, you can clear the localStorage). You'll have to register a message event listener on the localStorage.
The user authenticate/create a sensitive info on this tab (or any other tab opened on your domain).
You update the sessionStorage to store the sensitive information, and use the localStorage to store this information, then delete it (you don't care about timing here, since the event was queued when the data changed). Any other tab opened at that time will be called back on the message event, and will update their sessionStorage with the sensitive information.
If the user open a new tab on your domain, its sessionStorage will be empty. The code will have to set a key in the localStorage (for exemple: req). Any(all) other tab will be called back in the message event, see that key, and can answer with the sensitive information from their sessionStorage (like in 3), if they have such.
Please notice that this scheme does not depend on window.onbeforeunload event which is fragile (since the browser can be closed/crashed without these events being fired). Also, the time the sensitive information is stored on the localStorage is very small (since you rely on transcients change detection for cross tab message event) so it's unlikely that such sensitive information leaks on the user's hard drive.
Here's a demo of this concept: http://jsfiddle.net/oypdwxz7/2/
There are no such the way to detect browser close so probably you can't delete localStorage on browser close but there are another way to handle the things you can uses sessionCookies as it will destroy after browser close.This is I implemented in my project.
if(localStorage.getItem("visit") === null) {
localStorage.setItem('visit', window.location.hostname);
console.log(localStorage.getItem('visit'));
}
else if(localStorage.getItem('visit') == 'localhost'){
console.log(localStorage.getItem('visit'));
}
else {
console.log(localStorage.getItem('visit'));
}
$(document).ready(function(){
$("#clickme").click(function(){
localStorage.setItem('visit', '0');
});
});
window.localStorage.removeItem('visit');
window.addEventListener('beforeunload', (event) => {
localStorage.setItem("new_qus_id", $('.responseId').attr('id'));
var new_qus_no = localStorage.getItem('new_qus_id');
console.log(new_qus_no);
});
if (localStorage.getItem('new_qus_id') != '') {
var question_id = localStorage.getItem('new_qus_id');
} else {
var question_id = "<?php echo $question_id ; ?>";
}
you can try following code to delete local storage:
delete localStorage.myPageDataArr;