set cookie and show div on first visit then hide - javascript

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.

Related

How to only show pop up on first page load

I am trying to only display a pop up on the first page load, but in my current script it only shows the pop up if you refresh the page. The popup should display the first time you come to the page but not again.
<script type="text/javascript">// <![CDATA[
document.addEventListener('DOMContentLoaded', function() {
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 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(function() {
if(getCookie('popup') !== ''){
$('.popup-wrapper').css('display','block');
} else {
setCookie('popup','open',1);
}
$('.popup-close').click(function(){
setCookie('popup','close',1);
$('.popup-wrapper').css('display','none');
});
});
});
// ]]></script>
Any help would be greatly appreciated.
Is there a reason why you are using cookies?? If not you can use localStorage and write something a bit cleaner..
So for example
$(document).ready(function() {
// if localStorage doesnt have the shownPopUp item
if(!localStorage.getItem('shownPopUp')){
$('.popup-wrapper').css('display','block');
}
$('.popup-close').click(function(){
// set the shownPopUp item in localStorage
localStorage.setItem('shownPopUp', true)
$('.popup-wrapper').css('display','none');
});
});
});
No need for the getCookie function
Cookies are more used for server-side functions, where localStorage is better for client-side functions. So what will happen here is your users will never see the popup again unless they delete there localStorage
Just add localStorage.setTtem after showing the popup. And don't forget to make the .popup-wrapper display:none
if(!localStorage.getItem('shownPopUp')){
$('.popup-wrapper').css('display','block');
localStorage.setItem('shownPopUp', true);
}

add cookie if no cookie of that name exists jquery

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.

Why isn't my cookie storing?

I'm trying to set a cookie on a click event to see if a user has actually clicked the respective button. The button is as follows:
Click here
My js to set the cookie is:
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 "";
}
Then, I set the cookie on a click event:
$("#modalBTN").click(function(){
var clicked = "clicked";
setCookie("clicked", clicked, 30);
console.log(clicked);
});
My click event works. when I console.log(clicked) I see the cookie value, but when I refresh the page the cookie is no longer there.
I check it by:
if(getCookie("clicked") != ""){
//do something else
}
UPDATE
when I call getCookie("otherCookie") it works. But when I call getCookie("clicked") i get returned null. Am I only allowed to have one at a time?
Try this : https://stackoverflow.com/a/24103596/5445351
You can only use console to test the two functions : createCookie & readCookie
Do :
createCookie('ppkcookie','testcookie',7);
Open another page, check if it's still there :
var x = readCookie('ppkcookie')
if (x) {
console.log("ok");
}
Look if it's not your browser that delete cookies automatically.
I tried with Chrome and IE9.

Cookies in HTML page

So this code that i have works perfectly and exactly as i want it to. What is does is it takes the input "textmoney" and calculates how much money you make yearly. I have a link to another calculator that makes a more percise prediction. Basically i want to know how to have the website remember what the data input was on "textmoney" on the first page, so that when the user clicks on the more advanced calculator the website will remember the value of "textmoney" and the user won't have to type in the same data again. Do i use cookies?
Code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
var $demo = $('#demo');
var $textMoney = $('#textmoney');
var $moneydiv = $('#moneydiv');
$('#advanced').hide();
function getmoney(){
var money = $textMoney.val();
if (isNaN(money) || money === '') {
$demo.text('You aint enter no $$$$$$');
} else {
var dailyE = $textMoney.val() * 365;
$demo.text('$' + dailyE + ' per day');
}
}
// on enter key
$textMoney.keydown(function(e) {
if (e.which === 13) {
getmoney();
$('#advanced').show();
} else if ($(this).val() === '') {
$demo.text('');
$('#advanced').hide();
}
}).mouseover(function() {
$(this).css('border', '1px solid black');
}).mouseout(function() {
$(this).css('border', '1px solid grey');
});
// on click
$moneydiv.click(function(){
getmoney();
$('#advanced').show();
});
});
</script>
You may use HTML5 Web Storate:
// Store
localStorage.setItem("textmoney", $textMoney.val());
// Retrieve
$textMoney.val(localStorage.getItem("textmoney"));
From W3Schools:
The data in localStorage will not be deleted when the browser is closed, and will be available the next day, week, or year.
If you want to store the value just while the browser (or tab) is open. You can use sessionStorage instead:
// Store
sessionStorage.setItem("textmoney", $textMoney.val());
// Retrieve
$textMoney.val(sessionStorage.getItem("textmoney"));
If your browser desn't support HTML5, cookies are also good idea but be aware that some browsers can also have blocked cookies.
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 "";
}
// Store
setCookie("textmoney", $textMoney.val(), 999999 /* Expiration*/);
// Retrieve
$textMoney.val(getCookie("textmoney"));

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