I want to save user preferences on a javascript code - javascript

I have this javascript code that changes the style of the website. but this code changes the style only when you click on it. and after you refresh the page it returns to default. I want it to save the users prefrences. I really like the code and I do not want to change it with another one. can you please help.
<script type="text/javascript">
$(document).ready(function() {
$("#fullswitch").click(function() {
$("#chpheader").removeClass("compact");
$("#imgg").removeClass("compact");
$("#chpheader").removeClass("original");
$("#imgg").removeClass("original");
$("#chpheader").addClass("normal");
$("#imgg").addClass("normal");
});
$("#compactswitch").click(function() {
$("#chpheader").addClass("compact");
$("#imgg").addClass("compact");
$("#chpheader").removeClass("original");
$("#imgg").removeClass("original");
$("#chpheader").removeClass("normal");
$("#imgg").removeClass("normal");
});
$("#originalswitch").click(function() {
$("#chpheader").addClass("original");
$("#imgg").addClass("original");
$("#chpheader").removeClass("compact");
$("#imgg").removeClass("compact");
$("#chpheader").removeClass("normal");
$("#imgg").removeClass("normal");
});
});
</script>

<html>
<body>
<span id="t1">0</span>
<span id="t2">0</span>
<span id="t3">0</span>
<span id="t4">0</span>
<span id="t5">0</span>
<span id="t6">0</span>
<div id="result"></div>
<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("lastname", "Smith");
localStorage.setItem("first", "Smi");
// Retrieve
var c = document.getElementById("result").innerHTML = localStorage.getItem("lastname");
var b = document.getElementById("result").innerHTML = localStorage.getItem("first");
document.getElementById("t1").innerHTML = c;
document.getElementById("t2").innerHTML = b;
//localStorage.removeItem("lastname");
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage....";
}
</script>
</body>
</html>

There is a jQuery cookie plugin there are examples on that page as well so you can see how you can set and read a value from the cookie.
Once the value is read it's just a simple matter of loading the right theme.
var theme = $.cookie('name_of_selected_theme');
setTheme(theme);
function setTheme(themeName){
if(themeName == "One"){
...
}else...
}
However cookies only allow for 4KB of data and are passed in every HTTP call. A better idea many be localStorage. You can use YUI Storage Lite library which is < 3KB in size and you can easily use it to save data in browser localStorage and load from it. You can save at least 5MB of data using localStorage.
Example code from the link above:
YUI({
//Last Gallery Build of this module
gallery: 'gallery-2010.12.01-21-32'
}).use('gallery-storage-lite', function (Y) {
// For full compatibility with IE 6-7 and Safari 3.x, you should listen for
// the storage-lite:ready event before making storage calls. If you're not
// targeting those browsers, you can safely ignore this step.
Y.StorageLite.on('storage-lite:ready', function () {
// To store an item, pass a key and a value (both strings) to setItem().
Y.StorageLite.setItem('kittens', 'fluffy and cute');
// If you set the optional third parameter to true, you can use any
// serializable object as the value and it will automatically be stored
// as a JSON string.
Y.StorageLite.setItem('pies', ['apple', 'pumpkin', 'pecan'], true);
// To retrieve an item, pass the key to getItem().
Y.StorageLite.getItem('kittens'); // => 'fluffy and cute'
// To retrieve and automatically parse a JSON value, set the optional
// second parameter to true.
Y.StorageLite.getItem('pies', true); // => ['apple', 'pumpkin', 'pecan']
// The length() method returns a count of how many items are currently
// stored.
Y.StorageLite.length(); // => 2
// To remove a single item, pass its key to removeItem().
Y.StorageLite.removeItem('kittens');
// To remove all items in storage, call clear().
Y.StorageLite.clear();
});
});

I suppose you have two options, store the info client side, or store the info server side.
If you actually have a "user" server side (the person has to log in, yada yada yada), you can store this setting for the user (add some data to where ever the user info is stored).
If you don't want it that persistent, you can store it in local storage (not very browser friendly) or cookies. You really have no guarantee that these settings will stay around, as they are controlled by the browser, users can have their browsers set to never save this info.
Either way (client or server) you can read the setting and set the classes server-side and skip the javascript for changing the classes. Always better to do it on the server.

You may use HTML5 window.localStorage to store user preferences and trigger the corresponding layout changes.
Or use cookies as previously suggested.
Take a look at this article: http://diveintohtml5.ep.io/storage.html

Use cookies to store the users options.
http://www.quirksmode.org/js/cookies.html

Use localStorage to store the user preferences, and on reload load the preferences back in.
Here's a good tutorial.
How to write:
localStorage['someKey'] = 5;
How to read: var lastKeyValue = localStorage['someKey'];

use session storage
//set in session storage
$("#block-menu-menu-organisation > ul > li > a" ).bind( "click", function(evt) {
//in that case one expanded at the time
sessionStorage.clear();
var par = $(evt.target).parent();
sessionStorage.setItem(par.attr('id'),par.attr('class'));
console.log(par.attr('class'));
});
// //retrieve class from session
if(typeof sessionStorage!='undefined') {
$('#block-menu-menu-organisation > ul > li' ).each(function(i) {
if( $(this).attr('id') in sessionStorage) {
$(this).attr('class', sessionStorage.getItem($(this).attr('id')));
}
});
}

Related

How to pass a variable from current window to another window

First Page
<button onclick="refereceid_Transfer()">Try it</button>
<script>
function refereceid_Transfer() {
alert('test');
var referenceid = "jggd154278";
referenceid = btoa(referenceid);
//sessionStorage.setItem("sent", referenceid);
window.open("second.jsp", "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400");
}
</script>
Second Page
<p id="s1"></p>
<script>
$(document).ready(function(){
// var a = sessionStorage.getItem("sent",id);
alert(a);
});
</script>
I need to pass my reference id from one window to another window. I tried use session storage and local storage to pass variable and i have failed in both condition. is there new suggestion that i can pass my reference id to new window.
Thanks
You can try localStorage for this.
Add item which you want to pass on another page:
localStorage.setItem("key", "value");
On another page you can access through:
localStorage.getItem("key");
You can store object data as well in localStorage. Note that clear localStorage if you're storing some sensitive information.
And simpler option is to use query parameter, but I think you're not okay with it.
Or you can use sessionStorage:
sessionStorage.setItem("key", data);
window.open("page_url","_blank");
on another page use:
$(document).ready(function(){
var data = sessionStorage.getItem("key");
console.dir(data);
});
Note: 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 specific browser tab.
You can do it with local storage or you can pass it in query parameters and read the query parameters at 2nd page.
If you are doing server side rendering you can also use session storage.

Add paraments to back button redirect to previous url

Ok so I have this code that allows me to redirect the users on my current page to any other page when they click the back button
The code works fine but now I would like to pass the URLs parameters from the previous page to the redirected page so for example. Lets us say that the main page the user is on is www.example.com/ready&val=1&base=2&timeid=3&rfid=4
I would like the &val=1&base=2&timeid=3&rfid=4 passed on to the end of the domain that the user is being redirected to when they click the back button
<script type="text/javascript">
!function(){
var c_link = "www.example.com/time";
var t;
try{
for(t=0;10>t;++t)history.pushState({},"","#");
onpopstate=function(t){t.state&&location.replace(c_link)}}
catch(o){}
}();
</script>
So the user gets to www.example.com/time I would like the &val=1&base=2&timeid=3&rfid=4 to be and the end of it.
I would not use HTML5 history.pushState for this as it is not supported for IE9 and previous versions. But I can give you a better solution. You can use sessionStorage and performance.navigation.type.
sessionStorage is a storage type like localStorage but it only saves your data for the current tab.
Session storage can be used like this.
sessionStorage.setItem('key', 'value'); //saves the value
sessionStorage.getItem('key'); //gets the saved value
performance.navigation.type is the browser is the variable that hold users navigation info.
if(performance.navigation.type == 2){
//User is coming with back button
}
With the information above we can solve your problem easily.
Script on next page
var values = {
val: 1,
base: 2,
timeid: 3,
rfid: 4
}
sessionStorage.setItem('returnData', JSON.stringify(values))
Here is our main page.
if(performance.navigation.type == 2){
var backValues = JSON.parse(sessionStorage.getItem('returnData'));
//Do whatever you need with backValues
}
var c_link = "www.example.com/time&val=1&base=2&timeid=3&rfid=4";
Please try to pas the value through the url itself.

How can I redirect with extra information in jquery?

I'd like to perform a redirect, but I also wish to send additional information along with it.
I've tried to change the value of window.location.href but that doesn't seem to pass along the extra information.
I also get how I can do
$.get(
new_url,
{data : "mydata"},
function(data) {
alert('page content: ' + data);
}
);
and that will display the html content of the new page, but that doesn't help with actually getting there.
How can I achieve this?
Edit: I feel as if I must be phrasing this terribly because I'm pretty sure this is an easy/common task. This shouldn't be something that would require cookies - it should basically be like a post request (I think).
You have a few different options for this:
URI Variables - You can append extra data to the URL by appending a question mark (?) followed by a set of key-value separated by an ampersand (=) with each variable being separated by an ampersand (&). For instance, http://www.google.com/search?q=javascript+url+variables&ie=UTF-8 gives you a link to a Google search for "javascript url variables" using UTF-8 encoding. Your PHP code or JavaScript would need to handle passing along and processing these variables. If using JavaScript a nice library for processing URLs is URI.js or using PHP you can use the parse_url and http_build_query functions. You can use this with window.location.href; for instance: window.location.href = "http://www.google.com/search?q=javascript+url+variables&ie=UTF-8" (replace the Google URL with the one you created or set in a variable).
Storage API - You can use the localStorage or sessionStorage properties to store and retrieve information using JavaScript (information is stored in the user's browser - supported by IE 8 and newer and all other major browsers). Note that this is JavaScript only unless you grab the data with JavaScript and pass it to your PHP server through URL variables, form, AJAX request, etc.
Cookie - You can store additional information inside a cookie - however this is more difficult since you have to setup your variables as a parsable string (possibly JSON) and remember to encode/decode the string when setting/getting the cookie. I don't recommend this method.
IndexedDB API - This is a more advanced client-side/browser storage mechanism and currently only supported in IE 10 and newer (and nearly all other browsers). There are also still changes being made to the standard which means newer versions of browsers could break current implementations or be buggy. If all you need is simple key-value storage (not an SQL-like database) then you should stick with one of the above options.
You can use the window open method to redirect your user,and remember to use "_self"
window.open('url','_self');
Preferably you'd store the data in localStorage and fall back to a cookie (I really like js-cookie).
Here are the two helper functions you need to store and retrieve data:
function setMultiPageData(itemName, data) {
var dataStr = JSON.stringify(data);
var hasLocalStorage = typeof localStorage !== 'undefined';
if (hasLocalStorage) {
localStorage.setItem(itemName, dataStr);
}
else {
Cookies.set(itemName, dataStr, { path: '/' }); // path set to root to make cookie available on any page
}
}
function getMultiPageData(itemName) {
var data = null;
var hasLocalStorage = typeof localStorage !== 'undefined';
if (hasLocalStorage) {
data = localStorage.getItem(itemName);
}
if (!hasLocalStorage || data === null) {
data = Cookies.get(itemName);
}
var parsedObject = null;
try {
parsedObject = JSON.parse(data);
}
catch (ex) {
console.log(ex); // remove in production
}
return parsedObject;
}
usage:
var data = { first: 'this is the first thing', second: 'this is the second thing' };
setMultiPageData('stackoverflow-test', data);
// go to a new page
var retrievedData = getMultiPageData('stackoverflow-test');
if (retrievedData === null) {
console.log('something went wrong')
}
else {
console.log(retrievedData); // { first: 'this is the first thing', second: 'this is the second thing' }
}

How to make a web app retain information?

Ok... so a user enters info into the journal field and hits submit, and a function gets called on the information they have submitted, which I call changeTextComment(). That function calls another function and so on as the info is formatted and placed in the cue, as in a Facebook commentary.
I need this information saved so it can be recalled later, in local storage, making the app not refresh every time I restart it. So...
<script>
function appCache() {
// Check browser support
// this is experimental for local storage...
more here: http://www.w3schools.com/html/html5_webstorage.asp
if (typeof(Storage) != "undefined") {
localStorage.setItem(para);
// Retrieve
document.getElementById("journal").innerHTML = localStorage.getItem(para);
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
};
</script>
So looking at the appCache function it seems like it might work except I need to identify what the key variable is that will be stored and then retrieved.
I think this is the variable userInput, as any time the user hits the 'add to journal' button this variable is used to store the user input and then put into the changeTextComment() function.
I am wondering if this is the simplest way to deal with this whole thing... I do not yet understand databases, but wondering if that would be easier to learn.
In this case, I would add the function Appcache() to the function changeText() such that it caches the variable and then how would I set it up to then feed the value of the variable's cached info into changeText() upon launch of the app?
Every submission to the journal will have a unique value.
Heres the ChangeTextComment() Function... still sorting out how to use classes in css to simplify these functions:
function changeTextComment(){
// to be modified from the above to change the location of the dump
var userInput = document.getElementById('userInput').value;
// get the input from the user
var panel = document.createElement("div"); // create a parent divider for everything
// assignment of attributes
panel.setAttribute("class","panel panel-default panel-body");
panel.setAttribute("id","panelBody");
var para = document.createElement("P");
var t = document.createTextNode(userInput);
para.appendChild(t);
// add comment area
var c = document.createElement("INPUT");
c.setAttribute("type", "text");
c.setAttribute("id", "comment");
c.setAttribute("placeholder", "comment here");
c.setAttribute("class", "form-control input-lg");
// add comment button attempt -- success <> now try to put it in the textarea
var d = document.createElement("INPUT");
d.setAttribute("type","button");
d.setAttribute("class","btn btn-info active pull-right");
d.setAttribute("onclick","commentThis()");
d.setAttribute("value","Add Comment");
panel.appendChild(para); // this is where a comments piece would go
// place the item
var destination = document.getElementById("journal")
//destination.insertBefore(Commentaryarea, destination.firstChild);
//destination.insertBefore(panel, destination.firstChild);
destination.insertBefore(panel, destination.firstChild);
panel.appendChild(c);
panel.appendChild(d);
document.getElementById("userInput").value = "";
document.getElementById("userInput").focus();}
</script>
<script>
function setText(a){
document.getElementById("userInput").value = a
document.getElementById("userInput").focus();
}
</script>
When you say "stored locally", do you mean stored in the visitors browser, i.e. with only themselves being able to see it and retrieve it? Or do you want other users to be able to see the data, and/or the commenter to be able to see it if they log in later from another location?
If it's the latter then you need to store it on the server side, and you're going to need a database for that. If all you need is to store journal entries then mongoDB is easy to set up with javascript, but if you have a lot of relations (journal entries being associated with users, comments on entries being associated with users and entries, ect) then perhaps an SQL database would suit you better.

Saving several ID's to one jQuery cookie and retrieving all values later

I'm building an image gallery on WordPress and I want to add a save to lightbox or save to collection function so that I can collect images with a click of a button and then download all images as a zip later. It sorta like a shopping cart without actually buying the stuff that you want. I want it just to be a per session kind of thing so that you don't need to register to the site.
So on my images page, I put a Save to lightbox button and I want to save the ID of this image to a cookie and then I keep adding images to it until I'm done and will click a view lightbox button that will list all of my collected images.
I know how to set a cookie but I don't know how to append values to it.
function saveLightbox(ID){
$.cookie('the_cookie', ID, { expires: 7 });
document.getElementById("result").innerHTML = $.cookie('the_cookie');
}
Here's fiddle of roughly how I want it to work.
To append values to the jQuery cookie, first of all you have to enable the storage of objects. Then you initialize a variable holding the content of the cookie. If the cookie is empty then initialize an empty array. Next, you push the ID to the array. Finally, you store this array in the cookie.
The following code illustrates what it is said above:
function saveLightbox(ID){
$.cookie.json = true;
var idContainer = ($.cookie('the_cookie')) || [];
idContainer.indexOf(ID) === -1 && idContainer.push(ID);
$.cookie('the_cookie', idContainer, { expires: 7 });
document.getElementById("result").innerHTML = $.cookie('the_cookie');
}
Another thing to consider, is that once an ID is already stored in the cookie you might want to prevent adding it again, that is the reason for line 4. You can find the working example here: jsfiddle.
save an array and push id's to that array:
var ids = $.cookie('the_cookie') || [ ];
function saveLightbox(ID){
$.cookie('the_cookie', ids.push(ID), { expires: 7 });
console.debug(ids);
console.debug($.cookie('the_cookie'));
document.getElementById("result").innerHTML = JSON.stringify($.cookie('the_cookie'));
}
(can't test or demonstrate atm, jsfiddle is not available (for me).)

Categories