Js can read cookies but can't evaluate them - javascript

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.

Related

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);
}

javascript counter with cookies doesn't work

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;
}
}

Why can't I get a cookie into a variable and then assign a div the result? [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 6 years ago.
I am trying to get the value of a cookie into a global variable in which I can then place into div's by using document.getElementById.
Here is my code - it works prefectly in terms of the fact it remembers the cookie but it just won't do one line in particular which I have clearly outlined with a comment for you.
Here is all my code...
<!DOCTYPE HTML>
<html>
<head>
<script>
var globalVar = "";
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);
}
}
return "";
}
function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
globalVar = getCookie("username");
document.getElementById("demo").innerHTML = globalVar; /* THIS LINE DON'T WORK WHY NOT! THE ONE BELOW DOES IN THE CHANGE COOKIE FUNCTION DOES! */
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
function changeCookie() {
var user = getCookie("username");
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
document.getElementById("demo").innerHTML = user; /* THIS WORKS! */
}
checkCookie();
</script>
</head>
<body>
<div id="demo"></div>
<button onclick="changeCookie()">Change username</button>
</body>
</html>
Try calling checkCookie() right after the page has finished loading.
<body onload="checkCookie()">
Another way is to move the script tag to the end of the page, right before the closing tag of body like this:
<html>
<body>
<div id="demo"></div>
<button></button>
<!-- the rest of the page's HTML here -->
<script>
....
.... your script code here
....
....
checkCookie();
</scirpt>
</body>
</html>
You are only assign html into "demo" in the first part of the case statement, you need to add it to the second part, and assign the user variable, not the globalVar. Also place the code at the end of the body as suggested in other answers.
function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
globalVar = getCookie("username");
document.getElementById("demo").innerHTML = globalVar;
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
document.getElementById("demo").innerHTML = user;
}
}
}

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()">

Changing link color based on stylesheet function

I am a novice JavaScript programmer; any help would be greatly appreciated.
I have successfully implemented a script that allows users to switch from a "regular view" to a "high contrast view". The script is simply changing stylesheets.
I have also set up the script with a basic toggle: when a user clicks "High Contrast View" the link text changes to "Back".
However, I need to modify how the toggle works: rather than changing the link text, I need to change the link color.
I know that I can create a function with .style.color, but I am not sure how to integrate this in to my current script.
JavaScript:
function load_all() {
var cssval;
cssval = get_cookie("cssclass");
if (cssval == null || (cssval != "Normal CSS" && cssval != "High-Contrast-View")) {
cssval = "Normal CSS";
}
set_stylesheet(cssval);
}
function switchStyle(newtitle) {
set_stylesheet(newtitle);
finish_stylesheet();
}
function set_stylesheet(newtitle) {
var csslink;
if (newtitle == null) {
if (get_stylesheet() == "Normal CSS") newtitle = "High-Contrast-View";
else newtitle = "Normal CSS";
}
for (var i = 0; (csslink = document.getElementsByTagName("link")[i]); i++) {
if (csslink.getAttribute("rel").indexOf("style") != -1 && csslink.getAttribute("title")) {
csslink.disabled = true;
if (csslink.getAttribute("title") == newtitle)
csslink.disabled = false;
}
}
set_cookie("cssclass", newtitle, 28);
}
function finish_stylesheet() {
var nojsanchor, nojsspan, newtitle;
newtitle = get_stylesheet();
nojsanchor = document.getElementById("footer_nojslink");
nojsspan = document.getElementById("contrastToggle");
if (nojsanchor != null && nojsspan != null) {
while (nojsspan.hasChildNodes())
nojsspan.removeChild(nojsspan.childNodes[0]);
nojsspan.appendChild(document.createTextNode(newtitle == "Normal CSS" ? "high contrast" : "back"));
nojsanchor.href = "javascript:switchStyle('" + (newtitle == "Normal CSS" ? "High-Contrast-View" : "Normal CSS") + "')";
}
}
function get_stylesheet() {
var i, a;
for (i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled)
return a.getAttribute("title");
}
return null;
}
function accepts_cookies() {
document.cookie = "cookiecheck=true; path=/";
var cookies = document.cookie;
if (cookies.indexOf("cookiecheck") >= 0)
return true;
else
return false;
}
function set_cookie(name, value, days) {
var expire;
if (days > 0) {
expire = new Date();
expire.setDate(expire.getDate() + days);
}
else
expire = null;
document.cookie = name + "=" + escape(value) + (expire == null ? "" : ";expires=" + expire.toGMTString()) + ";path=/";
}
function get_cookie(name) {
var cookielist, cookie;
cookielist = document.cookie.split(";");
for (var i = 0; i < cookielist.length; i++) {
cookie = cookielist[i];
while (cookie.charAt(0) == " ")
cookie = cookie.substring(1);
if (cookie.indexOf(name + "=") == 0)
return unescape(cookie.substring(name.length + 1));
}
return null;
}
With your current code you should be able to do this:
document.getElementById("footer_nojslink").style.color = "#A6A6A6";
If you find yourself doing this kind of task frequently it's going to be worth your time to learn jQuery. It can sometimes make things simpler, and takes away most cross browser headaches. Here is a jQuery example for the specific example you are asking, changing link color;
$('#footer_nojslink').css('color','#A6A6A6');
easy
import the two (or more) stylesheets...
<head>
<link rel="stylesheet" href="style_1.css">
<link rel="stylesheet" href="style_2.css">
</head>
and then enable/disable them this way:
<script>
document.styleSheets[0].disabled=true;
document.styleSheets[1].enabled=true;
</script>
Now you can change the entire style of your site, not only the links.
https://developer.mozilla.org/En/DOM/Document.styleSheets

Categories

Resources