i want to make a cokkie which can save my selected region on netsoltech.com whenever user select the region on map it can save the cookie and when the next time user come on domain the automatic go to 1st time click region page i make this code
but the problem is when the user come on next time then 1st region selector page come then it can refresh and go to the region page.. not the automatic...
<script>
/*
Cookie script - Scott Andrew
Popup script, Copyright 2005, Sandeep Gangadharan
*/
function newCookie(name,value,days) {
var days = 10; // the number at the left reflects the number of days for the cookie to last
// modify it according to your needs
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString(); }
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/"; }
function readCookie(name) {
var nameSG = name + "=";
var nuller = '';
if (document.cookie.indexOf(nameSG) == -1)
return nuller;
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,c.length);
if (c.indexOf(nameSG) == 0) return c.substring(nameSG.length,c.length); }
return null; }
function eraseCookie(name) {
newCookie(name,"",1); }
function toMem(region) {
newCookie('region', region);
window.location= "http://www.netsoltech.com/"+region+"/index";
}
function remCookie() {
window.location= "http://www.netsoltech.com/"+readCookie("region")+"/index";
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function() {
remCookie();
});
</script>
Try this
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
//redirect here
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function checkCookie() {
var region = getCookie("region");
if (region != null && region != "") {
alert("redirect to " + region); //replace this with redirect
}
}
checkCookie(); //check this on page load
and the HTML
europe
JSFiddle
http://jsfiddle.net/YtF2B/6/
Related
I'm having trouble getting two cookie values and adding them to a form field on my website. Below is the script I've added, which also populates the values in JavsScript Console; however I can't get the cookie values into the form fields.
Form fields:
<input type="text" id="usource" name="usource" value="">
<input type="text" id="referrer" name="referrer" value="">
I've tried this JS to populate the "usource" and "referrer" field, but it doesn't seem to work. Am I missing something?
document.getElementById("usource").value = utmCookie.utm_source;
document.getElementById("referrer").value = utmCookie.referrer;
This is the script I'm using which saves UTM parameters in cookies whenever there are any UTM parameters in the URL. It also saves the initial referrer information in a cookie which is ever (365 days) overwritten.
var utmCookie = {
cookieNamePrefix: "",
utmParams: [
"utm_source",
"utm_medium",
"utm_campaign",
"utm_term",
"utm_content"
],
cookieExpiryDays: 365,
// From http://www.quirksmode.org/js/cookies.html
createCookie: function (name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
} else
var expires = "";
document.cookie = this.cookieNamePrefix + name + "=" + value + expires + "; domain=.mywebsite.com; path=/";
},
readCookie: function (name) {
var nameEQ = this.cookieNamePrefix + name + "=";
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, c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length, c.length);
}
return null;
},
eraseCookie: function (name) {
this.createCookie(name, "", -1);
},
getParameterByName: function (name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
console.log(name);
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if (results == null) {
return "";
} else {
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
},
utmPresentInUrl: function () {
var present = false;
for (var i = 0; i < this.utmParams.length; i++) {
var param = this.utmParams[i];
var value = this.getParameterByName(param);
console.log(param + ' = ' + value);
if (value != "" && value != undefined) {
present = true;
}
}
return present;
},
writeUtmCookieFromParams: function () {
for (var i = 0; i < this.utmParams.length; i++) {
var param = this.utmParams[i];
var value = this.getParameterByName(param);
this.writeCookieOnce(param, value)
}
},
writeCookieOnce: function (name, value) {
var existingValue = this.readCookie(name);
if (!existingValue) {
this.createCookie(name, value, this.cookieExpiryDays);
}
},
writeReferrerOnce: function () {
value = document.referrer;
if (value === "" || value === undefined) {
this.writeCookieOnce("referrer", "direct");
} else {
this.writeCookieOnce("referrer", value);
}
},
referrer: function () {
return this.readCookie("referrer");
}
};
utmCookie.writeReferrerOnce();
if (utmCookie.utmPresentInUrl()) {
utmCookie.writeUtmCookieFromParams();
}
I have this counter:
http://codepen.io/leticiamartinch/pen/YpJgqx
Here is the code:
var MAX_COUNTER = 1000000;
var counter = null;
var counter_interval = null;
var deadline = localStorage.deadline;
function setCookie(name,value,days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toGMTString();
}
else {
expires = "";
}
document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
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,c.length);
}
if (c.indexOf(nameEQ) === 0) {
return c.substring(nameEQ.length,c.length);
}
}
return null;
}
function deleteCookie(name) {
setCookie(name,"",-1);
}
function resetCounter() {
counter = MAX_COUNTER;
}
function stopCounter() {
window.clearInterval(counter_interval);
deleteCookie('counter');
}
function updateCounter() {
var msg = '';
if (counter > 0) {
counter -= 1;
msg = counter;
setCookie('counter', counter, 1);
}
else {
msg = "Counting finished.";
stopCounter();
}
var el = document.getElementById('counter');
if (el) {
el.innerHTML = msg;
}
}
function startCounter() {
stopCounter();
counter_interval = window.setInterval(updateCounter, 1000);
}
function init() {
counter = getCookie('counter');
if (!counter) {
resetCounter();
}
startCounter();
}
init();
I'd like it to decrease in a slower basis so that it doesn't seems to be a timer countdown but full number counter.
Let me guess that you want it to look like e.g. a download counter which has real underlying data instead of a timed counter where people can see that it is just an artificial countdown.
I'd suggest to generate two random numbers - one for the next time interval till decrease and one for the amount of decrease. Set the time interval to be random between - let's say 1 and 3 and the amount between 1 and 5 (depending on how fast you want the countdown to be). You probably want to experiment with the values. Also don't set an initial value of 1000000 because that looks rather obviously fake.
Such an implementation could make sense for example when creating a mockup for a customer where you later put the real underlying data, such that your customer gets a feeling on how the counter will behave later.
If I'm guessing wrongly on what you initially want - please let us know and provide more information.
Here is what you'll get:
var MAX_COUNTER = 1294652;
var counter = null;
var counter_interval = null;
var deadline = localStorage.deadline;
function setCookie(name,value,days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toGMTString();
}
else {
expires = "";
}
document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
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,c.length);
}
if (c.indexOf(nameEQ) === 0) {
return c.substring(nameEQ.length,c.length);
}
}
return null;
}
function deleteCookie(name) {
setCookie(name,"",-1);
}
function resetCounter() {
counter = MAX_COUNTER;
}
function stopCounter() {
window.clearInterval(counter_interval);
deleteCookie('counter');
}
function updateCounter() {
var msg = '';
if (counter > 0) {
newDecreaseAmount = Math.floor(Math.random() * 3) + 1;
counter -= newDecreaseAmount;
msg = counter;
setCookie('counter', counter, 1);
// set new interval
newInterval = (Math.floor(Math.random() * 5) + 1) * 1000;
counter_interval = window.setTimeout(updateCounter, newInterval);
}
else {
msg = "Counting finished.";
stopCounter();
}
var el = document.getElementById('counter');
if (el) {
el.innerHTML = msg;
}
}
function startCounter() {
stopCounter();
updateCounter();
}
function init() {
counter = getCookie('counter');
if (!counter) {
resetCounter();
}
startCounter();
}
init();
So I have this javascript game that works on my local server but once I put it online, one of the functions stops working. It may have something to do with permissions of the cookies I am storing for the high score. Can someone please point out what may be wrong.
//Save Highscore if score is greater
function saveScore() {
loadScore();
if (score > highscore) {
var date = new Date();
date.setMonth(date.getMonth() + 5);
var expires = "; expires=" + date.toGMTString();
document.cookie = "score=" + score + expires + "; path=/";
}
}
//Load High Score
function loadScore() {
var cookiearray = document.cookie.split(';');
for (var i = 0; i < cookiearray.length; i++) {
var name = cookiearray[i].split('=')[0];
var value = cookiearray[i].split('=')[1];
if (name == "score") {
//alert("Score Found!");
highscore = value;
}
}
return highscore;
}
//Lost game function
function Lost() {
saveScore();
loadScore();
var lost = document.getElementById("lost");
var hs = document.getElementById("hs");
lost.style.visibility = "visible";
postscore.innerHTML = score;
hs.innerHTML = highscore;
lost.addEventListener('click', function (event) {
window.location.reload();
});
}
Based on your comments, I'm guessing that you've modified your code over time but have always had a saved cookie since it became necessary to have one. In your code sample, if the cookie doesn't exist, highscore is never going to be assigned before it's used. You should have some function that runs on page load that looks for the cookie and if it doesn't exist, initializes the beginning state to known values.
Moreover, I would suggest that an object-oriented approach might be more robust. In particularly, I'd create a dedicated object for cookie-handling - which properly handles the case where the cookie doesn't exist - and a separate object or objects for the game.
From MDN - an example of a cookie handler
var docCookies = {
getItem: function (sKey) {
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!sKey || !this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: /* optional method: you can safely remove it! */ function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};
One potential implementation of the elements of your game as an object, loaded in an immediately invoked function that uses the cookie handler above.
(function(cookieHandler) {
// Game constructor
var Game = function(cookieHandler) {
this.init(cookieHandler);
};
// initializes the game variables, sets up and binds the event handlers
Game.prototype.init = function(cookieHandler) {
this.scoreCookie = 'score';
this.score = 0;
this.highScore = this.loadScore();
this.cookieHandler = cookieHandler;
this.lostElem = document.getElementById("lost");
this.postScoreElem = null; // don't see this defined anywhere
this.highScoreElem = document.getElementById("hs");
this.setUpHandlers()
.bind();
};
// create handlers for the events
Game.prototype.setupHandlers = function() {
this.lostHandler = this.lost.bind(this);
return this;
};
// bind the handlers to events
Game.prototype.bind = function() {
// there should probably be a binding for some event
// to invoke the lost handler (lostHandler)
this.lostElem.addEventListener('click', function (event) {
window.location.reload();
});
};
// save the current score, if higher than the current high score, to
// the game cookie
Game.prototype.saveScore = function() {
if (this.score > this.highScore) {
var date = new Date();
date.setMonth(date.getMonth() + 5);
this.cookieHandler.setItem(this.scoreCookie, score, date, '/');
}
};
// retrieves the high game score from the cookie, initializes it to zero
// if there is no cookie.
Game.prototype.loadScore = function () {
this.highScore = 0;
if (this.cookieHandler.hasItem(this.scoreCookie)) {
this.highScore = parseInt(this.cookieHandler.getItem(this.scoreCookie,10);
}
};
// when the game is lost, update the high and save the current score
// if it is a new high score. Signal that the game was lost.
Game.prototype.lost = function() {
this.loadScore();
this.saveScore();
this.lostElem.style.visibility = "visible"
// this.postScoreElem.innerHTML = score;
this.highScoreElem.innerHTML = highscore;
};
var game = new Game(docCookies);
)(docCookies);
I have a task to set the cookie for the menu.I have a horizontal menu.When I click on the menu the id of the menu is set in to the cookie.But when I am selecting the next menu cookie shows the first input value.For that I used $.removeCookie("activeDivId");.But it doesn't work properly.How can I solve this problem?
Html code is
<div class="menuBar">
<div id="divHome" class="menuHeader ui-corner-top">
<span>Home</span>
</div>
<div id="divNewTransaction" class="menuHeader ui-corner-top">
<span><a href="#" onclick="NewTransaction()" >New Transaction</a></span>
</div>
</div>
javascript file is
$(document).ready(function () {
$(".menuHeader").click(function () {
$.removeCookie("activeDivId");
$.cookie("activeDivId", this.id); });
alert(document.cookie);
var activeDivId = $.cookie("activeDivId") ? $.cookie("activeDivId") : "divHome";
$("#" + activeDivId).addClass("menuHeaderActive");
});
$(document).ready(function () {
//for debugging purpose, so that you can see what is in the menu cookie
$('#debug').html('Cookie Content : ' + readCookie('menu'));
//if cookie menu exists
if (readCookie('menu')) {
//loop through the menu item
$('#menu a').each(function () {
//match the correct link and add selected class to it
if ($(this).html() == readCookie('menu')) $(this).addClass('selected');
});
}
$('#menu a').click(function () {
//Set the cookie according to the text in the link
createCookie('menu', $(this).html(),1);
});
});
/* Cookie Function */
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
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,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
You Can Use this method instead of jquery Method
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
//var fixedName = '';
/// name =name;
document.cookie = name + "=" + value + expires + "; path=/";
this[name] = value;
}
function readCookie(name) {
var nameEQ = name + "=";
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, c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length, c.length);
}
return c;
}
function eraseCookie(cookiename) {
this.createCookie(cookiename, '', -1);
this[cookiename] = undefined;
// Ecookie(cookiename);
}
I am building html pages with a lot of checkboxes. I want to manage a single cookie containing selected items. Cookie looks like 1234^9876^3456^ where ^ is the separator.
When the user checks or unchecks the box, the cookie shows the added or removed id number.
Here are the functions I am using. All but the 2 last are from know third-party developers. Some problems are:
Each checkbox has an onclick event AddRemoveOrdinal2(...);
The user sees okay checked and unchecked summary data, even refreshing the page but several cookies are stored in browser, same name, path, different content;
The last function RemoveOrdinal is used to remove an item from the summary, it deletes the cookie and does not replace the new one.
Maybe it would be better to start again with a new idea/procedure
function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
function del_cookie(name)
{
if (dbug) alert('del_cookie');
document.cookie = name + '=' + '; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/; '
}
function get_cookie(name) {
if (dbug) alert('get_cookie');
var dcookie = document.cookie;
var cname = name + "=";
var clen = dcookie.length;
var cbegin = 0;
while (cbegin < clen) {
var vbegin = cbegin + cname.length;
if (dcookie.substring(cbegin, vbegin) == cname) {
var vend = dcookie.indexOf (";", vbegin);
if (vend == -1) vend = clen;
return unescape(dcookie.substring(vbegin, vend));
}
cbegin = dcookie.indexOf(" ", cbegin) + 1;
if (cbegin == 0) break;
} return null;
}
function set_array(name, ary, expires) {
if (dbug) alert('set_array');
var value = '';
for (var i = 1; ary[i]; i++) {
value += ary[i] + '^';
}
set_cookie(name, value, expires);
}
function AddRemoveOrdinal2(id, ordinal, id_checkbox){
var foo = document.getElementById(id_checkbox).checked;
if (foo == false) {
get_array(cookieName, myarray);
var myarray2 = init_array();
for (var i=0; i<next_entry(myarray); i++) {
if(myarray[i] != ordinal){
myarray2.push(myarray[i]);
}
}
del_cookie(cookieName);
set_array(cookieName, myarray2, expires);
myarray = myarray2;
// Code here to display:none/block
}
else {
get_array(cookieName, myarray);
myarray.push(ordinal);
set_array(cookieName, myarray, expires);
}
get_array(cookieName, myarray);
if(myarray.length > 1){
// Code here to display:none/block elements
}
else {
// Code here to display:none/block elements
}
function RemoveOrdinal(id, ordinal, id_checkbox){
get_array(cookieName, myarray);
var myarray2 = init_array();
for (var i=0; i<next_entry(myarray); i++) {
if(myarray[i] != ordinal){
myarray2.push(myarray[i]);
}
}
del_cookie(cookieName);
set_array(cookieName, myarray2, expires);
myarray = myarray2;
esconder(id);
document.getElementById(id_checkbox).checked=false;
get_array(cookieName, myarray);
if(myarray.length > 1){
// Code here to display:none/block elements
else {
// Code here to display:none/block elements
}
}
On load
var cookieName = 'ordinals';
var myarray = init_array();
var timeToKeep = 60000*60*24*7;
var expires = new Date();
expires.setTime(expires.getTime() + timeToKeep);
var x = get_cookie(cookieName);
if ( !x || x == null) {
set_array(cookieName, myarray, expires);
}