I have two html files: index.html and lobby.html. In main.js, which I load in index.html, lobby.html is loaded using window.location.href. I have tried every way of defining globals in main.js (namespaces such as: var Global = {}; Global.variableName = 0; ... Global.variableName = whatever;, simply defining variables out of function scopes: var myGlobal; and even using window. to define and use globals: window.myGlobal = 0; ... window.myGlobal = whatever;). No matter any of these approaches, every time I try to access these "globals" in a separate script in lobby.html, it always throws an undefined error. How does this make any sense?
The answer to your first question, Why can't I ...?, is that you start a new session whenever you load a page. So, any of the Javascript variables from the previous session are gone.
The other (implied) question, How can I keep the value of Javascript variables across sessions? is either to use cookies in Javascript (MDN) or append request variables to the end of your URL then process them when the new page loads: GET (SO)
When a new page is loaded, you are essentially starting a new session as explained by others here and hence the data will be reset. For retaining some data across pages, you could use HTML5 Web storage - Session storage or Local storage as per your business needs.
MDN source
The two mechanisms within Web Storage are as follows:
sessionStorage maintains a separate storage area for each given origin that's available for the duration of the page session (as long
as the browser is open, including page reloads and restores).
localStorage does the same thing, but persists even when the browser is closed and reopened.
W3Schools
HTML local storage provides two objects for storing data on the client:
~ window.localStorage - stores data with no expiration date
~ window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)
Related
I want to dynamically load an image using jQuery like this:
main.js
var slidersrc=""; //try to define global variable - not sure if this is correct
jQuery(document).ready(function() {
jQuery("#sliderimg").attr('src', slidersrc);
});
jQuery("#selection1").click(function() {
slidersrc='wp-content/themes/*****/slide1.png';
});
So the first time user access my website, the slider is empty. After user clicks on one of the selection areas, I set the global variable value. Then if user continues to navigate at my website to different pages, the user should be shown a slider image as a result of his selection.
However, this doesn't appear to work.
Am I correctly using the global variable in jQuery? Or is there a better way to save the user selection value in client side?
thanks!
Global variables do NOT survive from one page to the next. Each page starts an entirely new javascript context (all new global variables, functions, etc...).
If you want to save state from one page to the next, your options are:
Put the data in a cookie which you can read from each successive page when that page loads.
Put the data in a browser local storage which you can read with javascript from each successive page when that page loads (recommended option).
Store the data on the server and embed it in each page as it is served from the server.
You can read about how to read and write from browser LocalStorage here and here.
If you're planning on changing the slider image each time the user clicks, then perhaps you want to save an index into an image array in local storage. When the page loads, you read the current index from localStorage (or supply a default value if no value exists in local storage), then write back the current value to localStorage for the next page. If the user takes some action that causes the index to update to a new value, then you update your page and then write that new index into localStorage so the next page can read it from there and so on.
LocalStorage is a similar concept to cookies, but it's a bit easier to manage and more efficient (the data is not sent to the server with every page request).
With HTML5 and local storage, can JavaScript be used to save the state of a web page?
For example, some sites have increase font size buttons that are most likely controlled with JS. How can the property be saved so that on a refresh the size stays the same? Or is this done without JS?
Your best bet is probably to use localStorage, unless you do not want the settings to persist upon new sessions (you would use sessionStorage in that case). If you have multiple settings, you can store a serialized representation of your settings.
E.g.
var settings = {
fontSize: '11px',
otherConfig: 'test'
};
localStorage.setItem('settings', JSON.stringify(settings));
//then you can retrieve it
settings = JSON.parse(localStorage.getItem('settings'));
console.log(settings.fontSize); //11px
Note that if you want the settings to persist when users connects from multiple computers, you will have to use some server-side support.
Yes, it is done with Javascript. You can use
Cookies
Sessionstorage
This is a global object (sessionStorage) that maintains a storage area that's available for the duration of the page session. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.
Localstorage
localStorage is the same as sessionStorage with same same-origin rules applied but it is persistent.
The better/easier ones are sessionStorage and localStorage. The problem is that they aren't supported by old browsers.
Instead, dealing with cookies can be a nightmare, but they work on old browsers too.
Yes can save state to localStorage.
assume you have an object :
var settingsObj={
pageClass:'bigFont',
widgetSortOrder : [1,5,3,7]
}
You could save that whole object to one local storage key by stringifying the object. When page loads you would see if that key exists in localStorage and have your javascript do whatever it neds to with those settings
To stringify and store:
localStorage.setItem('mySettings', JSON.stringify(settingsObj) );
To retrieve from storage and convert to js object
var settings=JSON.parse(localStorage.getItem('mySettings'));
I have some pages, on the last page I need to know what choices a user made on the two last pages.
Like this:
a.html
User has three choices here that takes him/her to different urls. I need to somehow save this choice and use it later.
Example:
<script>globalVariable1="firstchoice"</script>
b.html
This is one of three choices page and here the User have 3-4 new choices that takes him/her to different urls. I also need to save this choice somehow for later use.
Example:
<script>globalVariable2="thirdchoice"</script>
c.html
This is the page where I need to know what choices the user has made earlier. To be able to link back to those exact pages if the user wants to go back in my breadcrumb-solution.
Example:
<script>
if(globalVariable1 == "firstchoice"){
//do this
}
if(globalVariable2 == "thirdchoice"){
//do this
}
</script>
Can I do this with some global variables in javascript or how can I solve this?
Thanks
You can use localStorage. A browser API that persists key/value pairs even if you navigate between pages, reload the page or close and reopen the browser.
//setting a value
localStorage["foo"] = "bar";
//getting a value
var x = localStorage["foo"];
Using sessionStorage will also work.
//setting a value
sessionStorage["foo"] = "bar";
//getting a value
var x = sessionStorage["foo"];
Wikipedias Web Storage article describes the difference between localStorage and sessionStorage as:
Data placed in local storage is per domain (it's available to all scripts from the domain that originally stored the data) and persists after the browser is closed. Session storage is per-page-per-window and is limited to the lifetime of the window. Session storage is intended to allow separate instances of the same web application to run in different windows without interfering with each other, a use case that's not well supported by cookies.
You will have to store cookies to track the user's state. Try cookie.js. It has a really simple key-value interface that you can read about on its GitHub page.
Web pages are stateless, so you cannot share global JavaScript variables between pages.
However you can set global variables for your page and containing modules by using the value of the cookie.
Your cookies will be available on all pages of your domain for the current browser.
Example:
//Page 1: Set cookie depending on user choice
$.cookie("choice1", ValueOfChoice1);
//Page 2: Get previous user choice
globalVariable1 = $.choice1("example");
You can read Setting cookies with jQuery if you want more details about how to use cookies.
you can use localStorage or sessionStorage.
Another choice if you're using some server-side language like PHP or Asp.Net is to sore those values in the user's session on the server.
I am new to html5 and js,if this is a very simple question, please forgive my ignorance.
But can someone please help me in figuring a solution for my case:
I have created some static html5 pages and also a offline database from my js code which is accessed across all the html5 pages.
Now i am trying to update the database from one page and want the updated database reflection across all the html5 pages.
Thanks in advance.
As you said it is offline db, store the values in some global variable before storing it in database. And in all other pages , rely on that global variable.So , if you have some data updated in page1, store it in some global variable also. And use that variable in all other pages.
To access the offline databases from several different pages, please make sure all your pages are in the same domain.
Create a fresh connection to the database on all your pages.
var db_conn = window.openDatabase( _ID_DATABASE_NAME, _ID_DATABASE_VERSION, _ID_DATABASE_DESC, _ID_DATABASE_SIZE );
All the parameters passed to the function should remain same.
In case the values you are trying to access are only a few name value pairs, try to use the concept of local storages. Following are the setter getter methods accessible across pages.
window.localStorage.setItem( 'myFirstLocalStorage_Name', 'myFirstLocalStorage_Value' );
var ls_value = window.localStorage.getItem( 'myFirstLocalStorage_Name' );
Hope you'll be able to get your values across pages.
The domain of both pages is needed to be same.
and w3c says
User agents may restrict access to the database objects to scripts
originating at the domain of the top-level document of the browsing
context, for instance denying access to the API for pages from other
domains running in iframes.
Let's say I have a page that refers to a .js file. In that file I have the following code that sets the value of a variable:
var foo;
function bar()
{
foo = //some value generated by some type of user input
}
bar();
Now I'd like to be able to navigate to another page that refers to the same script, and have this variable retain the value set by bar(). What's the best way to transport the value of this variable, assuming the script will be running anew once I arrive on the next page?
You can use cookies.
Cookies were originally invented by
Netscape to give 'memory' to web
servers and browsers. The HTTP
protocol, which arranges for the
transfer of web pages to your browser
and browser requests for pages to
servers, is state-less, which means
that once the server has sent a page
to a browser requesting it, it doesn't
remember a thing about it. So if you
come to the same web page a second,
third, hundredth or millionth time,
the server once again considers it the
very first time you ever came there.
This can be annoying in a number of
ways. The server cannot remember if
you identified yourself when you want
to access protected pages, it cannot
remember your user preferences, it
cannot remember anything. As soon as
personalization was invented, this
became a major problem.
Cookies were invented to solve this
problem. There are other ways to solve
it, but cookies are easy to maintain
and very versatile.
See: http://www.quirksmode.org/js/cookies.html
You can pass the value in the query string.
When the user navigate to the other page append the value to the query string and load it in the next.
Another option is jStorage. jStorage is probably better used for cached data and lossy user preferences (e.g. saved username in a login form), as it doesn't have full browser support (but IE6+ and most other common browsers support it) and cannot be relied upon (like cookies).
You can use YUI's Cookie Library http://developer.yahoo.com/yui/cookie/