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();
Related
I had some code created to convert a 3rd party form to jQuery AJAX with a custom redirect. On the redirect page the users name from the form was captured. The issue is that I can only capture the name once. If I try to duplicate the code to show the name multiple times it doesn't work.
Would much appreciate the help!
------Javascript for the submit button------
window.CFS = window.CFS || {};
(function () {
"use strict";
CFS.msgPleaseWait = 'Please wait...';
CFS.msgRedirect = 'Redirecting...';
CFS.nameField = '';
CFS.nameFromSubmitField = '';
CFS.redirectTo = '';
CFS.submitButtonText = '';
CFS.submitHandler = function(form) {
var $form = $(form);
var dataToPost = $form.serialize();
var urlToPostTo = $form.attr("action");
var $submitButton = $("input[type='submit']", $form);
CFS.submitButtonText = $submitButton.val();
CFS.disableSubmit($submitButton);
$.ajax({
type: 'POST',
url: urlToPostTo,
data: dataToPost,
success: function(data) {
if (CFS.redirectTo) {
$submitButton.val(CFS.msgRedirect);
if (CFS.nameField) {
var nameFieldVal = '';
if ($("input[name='" + CFS.nameField + "']", $form)) {
nameFieldVal = $("input[name='" + CFS.nameField + "']", $form).val();
}
if (nameFieldVal) {
CFS.setCookie('name', nameFieldVal, 60);
}
}
window.location.replace(CFS.redirectTo);
} else {
CFS.enableSubmit($submitButton);
}
},
error: function() {
console.log('Campaigner.com error!');
CFS.enableSubmit($submitButton);
}
});
}
CFS.disableSubmit = function($button) {
$button.attr("disabled", "disabled");
$button.val(CFS.msgPleaseWait);
}
CFS.enableSubmit = function($button) {
$button.val(CFS.submitButtonText);
$button.removeAttr("disabled");
}
CFS.setCookie = function(name, value, seconds) {
var d = new Date();
d.setTime(d.getTime() + (seconds * 1000));
var expires = 'expires=' + d.toUTCString();
document.cookie = name + '=' + value + ';' + expires + ';path=/';
}
CFS.getCookie = function(name) {
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);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return '';
}
CFS.setNameFromSubmit = function() {
if (CFS.nameFromSubmitField) {
var elem = document.getElementById(CFS.nameFromSubmitField);
var savedName = CFS.getCookie('name');
if (elem && savedName) {
elem.innerHTML = savedName;
}
}
}
})();
------Name Field Captured-----
<p>Hello my name is <span id="nameFromSubmit">NAME HERE</span>
<script src="custom-submit.js" type="text/javascript"></script>
<script type="text/javascript">
if ((typeof CFS !== 'undefined') && CFS.setNameFromSubmit) {
CFS.nameFromSubmitField = 'nameFromSubmit';
CFS.setNameFromSubmit();
}
</script>
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 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 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/
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);
}