add cookie if no cookie of that name exists jquery - javascript

I have a splash page where the user chooses between 2 experiences. once chosen, a cookie is added so they will always get that experience (or at least for the next 30 days). however, if a user comes to the site directly to a sub-url and bypasses the splash page, they should be automatically added to the default experience and get the default cooke (theme1). everything except the default cookie part is working.
here's what i have:
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;
}
$('.theme2').click(function() {
createCookie('chooseTheme','chosenTheme2',30)
});
$('.theme1').click(function() {
createCookie('chooseTheme','chosenTheme1',30)
});
var x = readCookie('chooseTheme');
if ($.cookie('chooseTheme') === null) {
createCookie('chooseTheme','chosenTheme1',30);
}
if (x.indexOf('chosenTheme1') > -1) {
$('body').addClass('themeOne');
} else if (x.indexOf('chosenTheme2') > -1) {
$('body').addClass('themeTwo');
}
thanks!

Try running a loop that updates every 1 minute. During the update, it triggers the function that checks for the cookie like the following:
setInterval(checkCookie(), 60000);
//the 60000 is for 60000 milliseconds which is 1 minute.
function checkCookie() {
var x = readCookie('chooseTheme');
if ($.cookie('chooseTheme') === null) {
createCookie('chooseTheme','chosenTheme1',30);
}
if (x.indexOf('chosenTheme1') > -1) {
$('body').addClass('themeOne');
} else if (x.indexOf('chosenTheme2') > -1) {
$('body').addClass('themeTwo');
}
}
Then add the code above into your code and it will check for the theme every 1 minute. I hope this helps you.

Related

How to add a value to a current cookie value

I'm doing an advert overlay for a website. The advert must be seen by the user 3 times consecutively in 24 hours. 24 hours after the advert was first seen(when the cookie was set) the cycle starts again
I have sorted out the 24 hour cookie expiry but I don't know how to implement the value system. Once the cookie value reaches 3 the advert hides
I'm open to a php solution
Here's the scripts that have been coded so far:
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);
}
<script type="text/javascript">
var days = 1;
var advert = document.getElementById('overlay-stage');
if (readCookie('seenAdvert')) {
advert.className = 'htmlNoPages hidden';
} else {
advert.className = 'htmlNoPages show';
createCookie('seenAdvert', 'yes', 1);
}
</script>
Any help would be greatly appreciated

How to disable popup from showing up on given page for 2 days after I click .popup-close on first visit to that page?

How to disable popup from showing up on given page for 2 days after I click .popup-close on first visit to that page ?
This is my code https://jsfiddle.net/4q1aL8pL/2/
I've tried localstorage between lines 122-140 in my code. I am javascript beginner please help :)
Maby there has to be some timer applied which will count to 2 days hours worth ?
//<![CDATA[
var n = Number(localStorage.getItem('odometerValue')) || 0;
var m = localStorage.getItem('displayNone');
var myOdometer;
function startcounting () {
var div = document.getElementById("odometerDiv");
myOdometer = new Odometer(div, {value: n, digits: 6, tenths: true});
myOdometer.set(n);
update();
}
function update () {
n=n+0.01
myOdometer.set(n);
localStorage.setItem('odometerValue', n);
localStorage.setItem('displayNone', m);
setTimeout(update, 200);
}
//]]>
you can use the local storage to save the date of when the pop up loaded.
var d = new Date();
this will stamp the current date then all you have to do is check with the date of the visitor again and if you minus them and it equals 2 days pop up again.
Here is a function for using cookies.
/* Show popup if cookie doesn't exist. Will hide for 2 days if closed */
var PopUpCookie = getCookie("MyPopUpCookie");
if (PopUpCookie == '') {
$('#odometerDiv').show();
} else {
$('#odometerDiv').hide();
}
}
$('.popup-close').on('click', function () {
$('#odometerDiv').hide();
setCookie("MyPopUpCookie", "hide");
});
function setCookie(cname, cvalue) {
var d = new Date();
d.setTime(d.getTime() + (2*24*60*60*1000)); /* 2 days */
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 "";
}

set cookie and show div on first visit then hide

I am trying to set multiple cookies depending on if the div exists via javascript but I have ran into an issue that I cannot figure out. On first visit, I would like to show the div to the user if the div exists then set a cookie (called redCookie) that expires in 3 days. After cookie is set on page refresh div should not be present. After 3 days I would like the div to be shown again redDiv.show().
At the moment the div shows on all page refreshes. The cookie is set but unfortunately it shows every time. Something must be wrong with my if statement but not sure what.
if ((redCookie = true) && (redDiv.length > 0))
Here is a link to js fiddle: https://jsfiddle.net/9uh96bh7/
Here are my functions:
$( document ).ready(function() {
colourCookies();
});
function colourCookies () {
var redCookie = getCookie("red-cookie-name");
var redDiv = $('.red');
var yellowCookie = getCookie("yellow-cookie-name");
var yellowDiv = $('.yellow');
if ((redCookie = true) && (redDiv.length > 0)) {
redDiv.show();
setCookie("red-cookie-name", redCookie, 3);
console.log ('red cookie is set');
} else {
redDiv.hide();
}
if ((yellowCookie = true) && (yellowDiv.length > 0)) {
yellowDiv.show();
setCookie("yellow-cookie-name", yellowCookie, 3);
console.log ('yellow cookie is set');
} else {
yellowDiv.hide();
}
}
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 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 "";
}
First, the code.
It should be if ((redCookie == true) && (redDiv.length > 0)) not if ((redCookie = true) && (redDiv.length > 0)).
= is assign, == means equal to.
Second, the logic part.
cookie isset -> hide div
cookie is not set -> show div, set cookie
(correct me if I miss understood.)
So the if statement should be:
if (redCookie == true){
//hide div
} else {
//show div
//set cookie
}
Third, you make a mistake when setting cookies.
you should set you cookie like setCookie("yellow-cookie-name", true, 3);
If you use setCookie("yellow-cookie-name", yellowCookie, 3); and yellowCookie is null, this will cause failure to your if statement.
I think problem is with setting cookie, as some of the browser like chrome not sets cookie when you are running it on local, if you host it on server or run it through visual studio, it will work.. Test once with hosting it in iis if possible, else you can use localStorage like below...
$( document ).ready(function() {
colourCookies();
});
function colourCookies () {
removeIfThreeDaysElapsed('red-ls');
removeIfThreeDaysElapsed('yellow-ls');
if (!localStorage.getItem('red-ls')) {
$(".red").show();
localStorage.setItem("red-ls", new Date().toGMTString());
} else {
$(".red").hide();
}
if (!localStorage.getItem('yellow-ls')) {
$(".yellow").show();
localStorage.setItem("yellow-ls", new Date().toGMTString());
} else {
$(".yellow").hide();
}
}
function removeIfThreeDaysElapsed(lsname){
var d1 = localStorage.getItem(lsname);
if(d1){
if(new Date() > new Date(new Date().getTime()+(3*24*60*60*1000))){
localStorage.removeItem(lsname);
}
}
}
You may need to edit the code to handle all the scenarios!
If you able to see the cookie in browser, then please try with check like below...
if (redCookie) {
redDiv.hide();
} else {
redDiv.show();
setCookie("red-cookie-name", true, 3);
}
Because when you are getting value back from cookie its datatype is not boolean, it gets converted to string, so either you check like above or can use redCookie === "true".
Hope this helps you.

Why does my cookie script not work?

I cant find out what is wrong with my cookie script on this site:
http://lampen.identitest.dk/
If you go to my site, you will find a hidden
<div id="popupDiv">
it does not show because of display: none in css but it should be showing and then if you click on a button it should be hiding in 24 hours.
this is my script:
$(document).ready(function() {
// If the 'hide cookie is not set we show the message
if (!readCookie('hide')) {
$('#popupDiv').show();
}
// Add the event that closes the popup and sets the cookie that tells us to
// not show it again until one day has passed.
$('#close').click(function() {
$('#popupDiv').hide();
createCookie('hide', true, 1)
return false;
});
});
// ---
// And some generic cookie logic
// ---
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);
}
I have found the cookie script on
http://jsfiddle.net/FcFW2/1/
and this is tested and works in a default html document with jQuery on.
I hope someone can help me out :)
Best regards Shane
There is a typo in your script tag declaration.
It should be <script type="text/javascript">
Currently it's <script type="type/javascript">
I don't see any errors in your code.

Checking Display Value of HTML element and saving to a Cookie in jQuery

I am currently trying to use jQuery to toggle the appearance of a shoutbox and remember the state (hidden / visible) from page to page. The problem I am having is in getting a cookie set to remember the state.
The code I have so far is below, but it doesn't seem to be executing the if statement correctly. Any ideas why?
function show_shoutbox() {
$('#SB').toggle("fast");
if ($('#SB').css('display') == "none") {
document.cookie = "displaysb=false;";
} else {
document.cookie = "displaysb=true; ";
}
}
I am fairly new to JavaScript and jQuery - so I apologize in advance if the answer is obvious. I'm hoping to learn.
Try
if ( $('#SB').is(':visible') ) {
...
}
It's normalized to work a little better than checking display.
document.cookie doesn't work that way. Check out:
http://www.quirksmode.org/js/cookies.html
It even has code at the end of it:
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);
}
use $('#SB')[0] instead of $('#SB').
this part of code returns an array of all elements that satisfy the requirements.
and if you only have one element with this ID, the first element with the index 0 is the element you are searching for.
Cache your element for efficiency
var sb=$('#SB');//cache once outside the function
function show_shoutbox() {
sb.toggle("fast");
if ( sb.is(':visible')) {//do your business
}
else { //do something else
}
}

Categories