javascript counter with cookies doesn't work - javascript

I just tried to make a timer with cookies that makes a button only 3 times clickable (I had to do it with cookies cause it refreshes the page in its process), I made this timer but it doesn't work. Nothing on my page changed at all.
The code I have by //something else happens gets executed by the program.
Timer - (or at least what I thought that would work as a timer) :
mailagain.onclick = function () {
if (typeof getCookie("countIt") !== 'undefined') {
if (checkCookie("countIt") > 3) {
// something happens
} else {
//something else happens
var counter = checkCookie("countIt") + 1;
setCookie("countIt", counter, 1)
}
} else {
setCookie("countIt", 1, 1)
}
};
Coockie functions :
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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 "";
}
function checkCookie(name) {
var value = getCookie("name");
if (value != "") {
return value;
}
}

Some issues:
When reading the value from the cookie, be aware that it has the string data type. You need to convert it to number before comparing it with another number or adding 1 to it.
The function checkCookie is using the wrong (hard-coded) cookie name, but is even not necessary as a function. You can do all that with getCookie.
Here is a working version:
mailagain.onclick = function () {
// make sure to convert to number (unitary plus), or use 0 when it is not a number:
var counter = (+getCookie("countIt") || 0) + 1;
setCookie("countIt", counter, 1)
if (counter > 3) {
console.log('clicked too many times! (', counter, ')');
} else {
console.log('clicked ' + counter + ' number of times.');
}
};

var value = getCookie("name");
getCookie always return "undefined" because of wrong cookie name. Remove brakets.
function checkCookie(name) {
var value = getCookie(name); //here you go
if (value != "") {
return value;
}
}

Related

How to reset Time Countdown with logout?

I have created online quiz with MVC5 each question in single page the time countdown start when student start his exam from question one to end of exam.
this is the script:
<script type="text/javascript">
javascript: window.history.forward(1);
</script>
<script>
var timeoutHandle;
function countdown(minutes, stat) {
var seconds = 60;
var mins = minutes;
if (getCookie("minutes") && getCookie("seconds") && stat) {
var seconds = getCookie("seconds");
var mins = getCookie("minutes");
}
function tick() {
var counter = document.getElementById("timer");
setCookie("minutes", mins, 10)
setCookie("seconds", seconds, 10)
var current_minutes = mins - 1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
//save the time in cookie
if (seconds > 0) {
timeoutHandle = setTimeout(tick, 1000);
} else {
if (mins > 1) {
setTimeout(function () { countdown(parseInt(mins) - 1, false); }, 1000);
} else {
window.location.replace("/StudentControl/LogOut");
return false;
}
}
}
tick();
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 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 = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
window.location.replace("/StudentControl/LogOut");
}
}
return "";
}
window.onload = function startingTimer() {
//countdown(prompt("Enter how many minutes you want to count down:"),true);
var reqt = $("#reqtimer").val();
countdown(reqt, true);
}
</script>
every thing is working fine the problem is:
if the student end early and logout and other student use his computer ,login and start his exam the time will continue from the last time for the pervious student.
Is there any way to reset the browser history or reset the countdown with logout command?

Run script with timeout once per session (but you could reload page and go to another page)

I've got a simple script, that I need to run only once per session of user. But in this session he could refresh page, or go to another page on one site.
My code now looks like this, but if user refresh page (in less then 10 seconds) or go to another page - script will never run :(
var visited = sessionStorage.getItem('visit');
if (visited == null || document.location.href == sessionStorage.getItem('lastPage')) {
setTimeout(function() {
alert('Hello World')
}, 10000
)
sessionStorage.setItem('visit', 1);
};
Working example: https://codepen.io/zavtraleto/pen/GdRpRZ
I think it's something with cookies, maybe
I made it using cookie, so if everyone interested:
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
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 = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}
getCookie('user_first_visited') || setCookie('user_first_visited', Date.now());
if (!getCookie('user_popup_triggerred')) {
var loopDetect = setInterval(function(){
var TimePast = (Date.now() - getCookie('user_first_visited')) / 1000;
if( TimePast > 5){
if (localStorage.getItem('surveyOnce') !== 'true') {
(function() {
alert('Hello World!')
}
)();
localStorage.setItem('surveyOnce','true');
};
}
}, 1000);
}

Detect if cookies are enabled in the browser

The code below works in all current browser except for IE. In IE the message doesn't display.
if (navigator.cookieEnabled == 0) {
document.write("Cookies are not enabled.");
}
Can someone tell me what I can do to make the above code work in IE 10 & 11?
I've tried code that works in IE but then it works in most browser except for Safari. Here's the code.
<script type="text/javascript">
if(/MSIE \d|Trident.*rv:/.test(navigator.userAgent))
var cookies = ("cookie" in document && (document.cookie.length > 0 ||
(document.cookie = "test").indexOf.call(document.cookie, "test") > -1));
document.write(cookies ? "" : "Cookies are not enabled.");
</script>
But this still displays for FF, Safari, and Chrome. So then I have two messages displaying....
This will do it:
$(document).ready(function () {
var event = window.attachEvent || window.addEventListener;
if (!trySetCookie()) {
// cookies are disabled
}
else{
// cookies are enabled
}
}
function trySetCookie() {
setCookie("testCookie", "testValue", 1);
var cookieValue = getCookie("testCookie");
if (cookieValue == "" || cookieValue == null)
return false;
return true;
}
// set a test cookie in the user's browser
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
// read the test cookie
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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 "";
}
"$(document).ready()" in JavaScript

Js can read cookies but can't evaluate them

I have made a webpage that asks user's that if they want to enable an effect, if they say yes then i store that "YES" as a cookie effect=true or if they don't want it then i also store it as effect=false cookie. The problem is listed as steps below:
User visits a webpage (first time)
He is alerted with document.cookie which is "".
He Clicks OK
Now value of saveedd is "", So according to my code the code below // Checkpoint 2 Should execute as value of saved is neither true nor false.
But instead It executes only 1 line of code below // Checkpoint 1 , This should not happen as value of saveed is not false.
What am I doing Wrong?
Note : I have stripped some code, So if you find any mistakes like var not defined ,Please comment
index.html
<html>
<head>
<title>My Second Page</title>
</head>
<body onload="askk()">
</body>
</html>
script.js
function askk() {
var saveedd = getCookie('effect');
alert(saveedd);
if (saveedd == true) {
changge();
alert('i wil change');
} else if (saveedd == false) {
// Checkpoint 1
alert('i will not change');
} else {
// Checkpoint 2
document.cookie = "effect=;expires=Wed; 01 Jan 1970";
var z = confirm("Enable Bgcolor Effect?");
if (z) {
changge();
}
setCookie("effect", z, 30);
}
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 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 = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) != -1) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
function changge() {
window.setInterval("Farbe()", 500);
}
farbe = 1;
function Farbe() {
if (farbe == 1) {
document.bgColor = "indigo";
farbe = 2;
} else if (farbe == 2) {
document.bgColor = "red";
farbe = 3;
} else if (farbe == 3) {
document.bgColor = "green";
farbe = 4;
} else if (farbe == 4) {
document.bgColor = "blue";
farbe = 1;
}
}
In comparison if (saveedd == false) string saveedd casting to bool type, empty string in JS casting to false. You should compare string with string like this: (saveedd == 'false')
You are comparing with the == operator, which coerces variables to be the same type before comparison. Hence, the value saveedd, which is the empty string '' will be converted to false. This is why Checkpoint 1 is being executed.
You will need to compare using the triple equals ===. This will preserve the type of the variables you are comparing, so saveedd == false will only be true if saveedd is false, not 0, '', [] or another "falsy" value. See Which equals operator (== vs ===) should be used in JavaScript comparisons? for more information.
Edit:
As weeklyTea mentions, you are also comparing against the boolean true and false. You may need to compare against the strings "true" and "false" instead.

Pop up once every 30 days

I am totally novice for JS and cookies. I got this code online and tried to change it for 30 days (it was set to 365) but it's probably resetting the cookie for every page and the pop up appears if I go to other page or even return back to the original page. Only things I changed in the code was expire days to 30 and load delay of 30 secs.
It seems either it's resetting the cookie every time I move to other page or some other problem which I don't understand yet :). I was wondering if there is some more efficient way to have it rather putting the code in every html article page. Something like setting up a cookie in headers or something and recalling using body onload.
Here is the code:
<SCRIPT language=JavaScript>
<!--
var expDays = 30; // number of days the cookie should last
function GetCookie (name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg)
return getCookieVal (j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function SetCookie (name, value,expires) {
var argv = SetCookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : null;
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;
document.cookie = name + "=" + escape (value) +
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain)) +
((secure == true) ? "; secure" : "");
}
function DeleteCookie (name) {
var exp = new Date();
exp.setTime (exp.getTime() - 1);
var cval = GetCookie (name);
document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}
var exp = new Date();
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
function getCookieVal(offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
function checkCount() {
var count = GetCookie('poponce');
if (count == null) {
count++;
SetCookie('poponce', count, exp);
// Action to take
dothis()
}
}
setTimeout(function dothis(){
var windowprops = "left=300,top=240,width=600,height=400,location=no,toolbar=no,menubar=no,scrollbars=no";
window.open("/subscribepopup.html", "", windowprops); // Use to load a page
}, 30000);
// -->
</SCRIPT>
<body OnLoad="checkCount()">

Categories

Resources