store a var local on a pc with javascript - javascript

I am trying to store the highscore of a player local, on his pc itself. I don't know if this is possible and I didn't find a question about it on this site. I just have a var wich contains a number. I want to store it on his pc soo when the player plays the game again in his browser his highscore still will be available.

use localstorage:
window.localStorage.score="20" // storing
window.localStorage.score // getting the score again.

localStorage is not supported by old browser . so use cookie as a fall back.
if(window.localStorage)
window.localStorage.setItem("highscore",1000);
else
document.cookie="highscore=1000; expires=Thu, 31 Dec 2018 12:00:00 UTC";
to retrieve the value
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0)
return c.substring(name.length,c.length);
}
return "";
}
if(window.localStorage)
var highscore=window.localStorage.getItem("highscore");
else
var highscore=getCookie("highscore");

It's a bit of an odd thing to do, unless we are talking about nodeJS (?) storing to file system or some other local store.
if you'de like to persist a certain value so next load it'll be taken from a stored location on javascript you'll have to do it using cookies,
but than again it'll be cleared every time you are clearing your cookies and will no be shared across multiple browser on your machine.
that being said, this is how you store a value to a cookie using javascript:
document.cookie="somekey=savedValue";
var readValue = document.cookie;

You can also use Cookies besides localStorage.
var expDate=new Date();
var score=20;
expDate.setDate(expDate.getDate()+365); // expiration after one year
// Setting cookie
document.cookie='score='+score+';expires='+expDate;
// Retrieving the cookie
var yourOldScore = document.cookie.match(/score=(.*?)\;/)[1];

Related

How to make a global variable have a different value with each html page?

I am creating a game (like 4 pics 1 word) and it involves having an answer variable. There will be a button that onclick will run a function that checks the user's answer if it matches the value of this variable. There will be one puzzle per page and each puzzle/page will have a different value for answer variable. This variable must have its value set when the page loads. I looked it up and I don't see anything that would help me and I have no idea how I would do this. Thanks in advance.
You might need either localStorage or use Cookies for this case. If you are targeting modern browsers, you are free to use localStorage, which is a concept of HTML5.
When you are using the click event, use this:
localStorage.setItem('scores', [scores-array]);
And then when you are loading the page, try this:
localStorage.getItem('scores');
To learn more about localStorage, use this:
MDN
Dive Into HTML5 - LocalStorage
The other option of Cookies, depends on your browser's privacy settings. Many browsers (not many) would probably disable cookies, but you can use it as an alternate. You have limited data type storage (only strings), which can be initiated using:
document.cookie="scores=" + score_data;
And retrieving them using:
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
getCookie(scores);

Using History object/javascript to redirect the user to a specific anchor when they press the back button?

I'm currently having an issue where the user is browsing a page with a long list of items with brief detail all laid out in a table. If the user wants to see more information about the item, they can click the link to view specific details on a separate page. Each tag has a unique id attribute. The problem I'm having is that when the list is very long (perhaps > 100 items) if the user wants to take a look at an item and then wants to click the back button, it takes them to the top of the previous page, losing their spot in the list.
I know there are a handful of solutions from the user's end like middle-click/open in new tab, from a website design standpoint (allow a smaller number of results in the table so they don't run into the problem of being so hard to find the spot they were at when they click the back button), etc.
I tried looking into using the History object and javascript, and thought I had seen somewhere that I could replace the LAST history entry, but all I can find are how to replace the CURRENT history entry. Ultimately what I'm looking to do is replace where the back button would normally take me to with that same url with the anchor of the element appended to the end.
i.e. If the user is on www.website.com/listAllItems and clicks the link for an item to go to www.website.com/viewItem?itemId=1234, I would like to change the last history entry to be www.website.com/listAllItems#1234 or similar.
Am I misunderstanding how the History object works? I'm hoping to be able to accomplish this without the use of a library. It seems like I've been VERY close to a solution several times, but it's always just a tiny bit off. Any help would be greatly appreciated!
I just use a cookie. I save the id of the last clicked item in the cookie, and then on load I get the id from the cookie, use that to query the dom for the element, and then set focus to it. i also used JQuery in my personal project, so i converted into straight JS for this answer since the question is tagged as javascript, i hope my conversion is alright.
function setCookie(cname, cvalue) {
var d = new Date();
d.setTime(d.getTime() + (1 * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = $.trim(ca[i]);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
element.attachEvent('onclick', function() {
setCookie(document.URL + '-lastclick', element.getAttribute('id'))
});
window.onload = function() {
var elementId = getCookie(document.URL + '-lastclick');
document.getElementById(elementId).focus();
// personally i do a .animate({ scrollTop: pos}) to scroll to my object, but you get the gyst.
}

javascript jquery mass delete cookies have similar name?

I'm looking for way to remove all my web cookies which have similar name "SID12345UID123456789" , all have SID and UID in their name ..
it can be done by jquery or pure JavaScript
thanks for any advices
Update: worked
base on other script i made this one it work but simple with indexOf .. i know some one can do better by regex match ..
please help
var cookies = document.cookie.split(";");
for(var i=0; i < cookies.length; i++) {
var equals = cookies[i].indexOf("="),
name = equals > -1 ? cookies[i].substr(0, equals) : cookies[i];
if ( name.indexOf('SID') > 0 && name.indexOf('UID') > 0 ){
alert(name);//for test
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
}
If you are creating these in your own code, you should delete the existing one before creating the new one (thus avoiding the problem).
Otherwise you can use a function like one found on this page. Run a loop that looks for a cookie with that name. If it finds it, delete it and then look again (until there are none left).

Javascript problems

First off, let me preface this question by saying that my professor is firmly entrenched in the past. Our last assignment required us to float links on top of pictures.
You might also say that he's insane as in order to test our pages he requires that all functionality (including cookies) be implemented with "client side technology" i.e. not on the server. He uses Firefox to test the pages, so the single blessing is that he doesn't care about cross-browser compatibility.
That being said, I'm having a problem with our latest assignment. We're making a "shopping cart" system using Javascript and cookies to store the items to be purchased. This is fine, except for some reason in my function that adds a new element to the cookie, assigning something to document.cookie doesn't work.
You can find my entire site here .zip file download (if there's anything that you wonder, "why on earth would you do that? That's crazy!" - that's either a direct assignment or a way to try and minimize the pain.)
This is my code in question that should be modifying the cookie:
var mycookies = new function (){
var cookies = document.cookie.split(';');
var cookie, values;
this.items = [];
for(var x = 0; x < cookies.length; x++){
if(cookies[x] != ""){
cookie = cookies[x].split('=')[0].trim()
values = cookies[x].split('=')[1]
values = values.split(',');
if(!this.items[cookie]){
this.items.push(cookie);
this[cookie] = new function(){};
}
this[cookie].size = values[0];
this[cookie].qty = parseInt(values[1]);
}
}
this.render = function(){
var values, cookies = "", cookie;
for(var x = 0; x < this.items.length; x++){
cookie = this.items[x];
values = [this[cookie].size, this[cookie].qty].join(',');
cookies += cookie + "=" + values + '; ';
}
return cookies;
}
this.clear = function(){
for(var x = 0; x < this.items.length; x++){
delete this[this.items[x]];
}
this.items = [];
document.cookie['expires'] = '26 Aug 1984 01:01:01 UTC;';
}
this.additem = function(){
var i = document.forms[0].size.selectedIndex;
if (this.items[page]){
this[page].size = document.getElementById('size').value;
this[page].qty = document.getElementById('qty').value;
}
else{
this.items.push(page);
this[page] = new function(){};
this[page].size = document.getElementById('size').value;
this[page].qty = document.getElementById('qty').value;
}
console.log(this.render()); // For use with firebug
document.cookie = this.render();
console.log(document.cookie); // For use with firebug
}
}
When I fire this off, firebug provides this output:
expires=12 Aug 2001 01:01:01 UTC,NaN; whitec=Small,3;
expires=12 Aug 2001 01:01:01 UTC,NaN
Now, I would expect 1) my cookie to have expired (I set the expiration manually through firebug, my parsing added the NaN later, - yet there it stays), and 2) the value for the cookie to be changed to the result of this.render()
Other than the obvious fact that client-side cookie behavior is not guaranteed by the w3 spec, am I missing something here? (EDIT - what I mean is when the page is client-side, opened as a file - not served by a server) This is really aggravating - I've tried a multitude of different angles, and no "javascript cookie" search or "modify cookies javascript" leads me to anything useful. Any suggestions about how I can fix it?
Or should I just email my professor with a link to the w3 specs and tell him that requiring us to support cookies client side is stupid?
The workings of document.cookie are not what you apparently think they are. When you set a value into the variable, you set one cookie at a time. Thus, if you wanted to set all the cookies you're holding in your object, you'd loop through your "items" array and set document.cookie successively to each name/value pair (transformed into a "cookieName=cookieValue" string).
This is a fact in all modern browsers. See this Mozilla documentation page for example.
Other comments on the code, since you were nice enough to post it:
cookie = cookies[x].split('=')[0].trim()
values = cookies[x].split('=')[1]
Better to call "split" just once.
this[cookie] = new function(){};
That's essentially equivalent to this[cookie] = {}; to set the property to a new empty object.
Looks something may be bad with the dates ?
Try to set expiration time in the far future when setting the cookie.
Your programming class sounds a bit strange.
But in my experience, manipulating cookies on the client side is really well supported in the browsers.
Quirksmode has a great article about cookies with some examples of helper functions to set and read cookies: http://www.quirksmode.org/js/cookies.html

Reading cookie value in Rails

I successfully set a cookie in JavaScript:
var date = new Date();
date.setTime(date.getTime()+(1*24*60*60*1000)); //one day expiration date
var expires = "; expires="+date.toGMTString();
window.name = date.getTime();
document.cookie = "window_name="+window.name+expires+"; path=/";
Then in rails I try to read (I've tried both of the following):
cookies[:window_name]
request.cookies['window_name']
both of which have an empty value.
How can I access the window_name cookie that I set in the Javascript?
I had exactly the same problem, cookie with no value on the rails side...
It seems that cookies set with JavaScript need to be in the path of your controller.
Let say you want to use cookies[:window_name] in the users controller, you need to do :
document.cookie = "window_name="+window.name+expires+"; path=/users/";
Must be security stuff...
I don't what you could do if you want to use that cookie in several controllers, luckily I don't !

Categories