Cookie value to define style on page load - javascript

I am using the scripts from here http://www.quirksmode.org/js/cookies.html and have successfully created a cookie.. it is set based on the users response to the age drop down. However I am having trouble doing anything with it. I would like to have a style defined if a cookie is present. Here is the bulk of my scripts..
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 checkAge(){
var min_age = 13;
var year = parseInt(document.forms["emailForm"]["year"].value);
var month = parseInt(document.forms["emailForm"]["month"].value) - 1;
var day = parseInt(document.forms["emailForm"]["day"].value);
var theirDate = new Date((year + min_age), month, day);
var today = new Date;
if ( (today.getTime() - theirDate.getTime()) < 0) {
var el = document.getElementById('emailBox');
if(el){
el.className += el.className ? ' youngOne' : 'youngOne';
}
document.getElementById('emailBox').innerHTML = "<style type=\"text/css\">.formError {display:none}</style><p>Good Bye</p><p>You must be 13 years of age to sign up.</p>";
createCookie('age','not13',0)
return false;
}
else {
createCookie('age','over13',0)
return true;
};
};
window.onload=function(){
var x = readCookie('not13');
if (x) {
document.getElementById('emailBox').innerHTML = "<style type=\"text/css\">.formError {display:none}</style><p>Good Bye</p><p>You must be 13 years of age to sign up.</p>";
}
}
Age verification works and cookie is set.... no errors (from Firebug).. can anyone see what I am doing wrong?

with jQuery would be something like this
if (x) {
var style = "<style type=\"text/css\">.form {display:none}</style>";
$("header").append(style);
}

Looking at your code it should work. There's nothing incorrect about it.
The only thing I would suggest is that instead of injecting a style tag into a empty div, inject a link tag into the head. This will mean that your css changes and maintainance won't need to touch the js code.

I got it.. I was looking for the cookie value and needed to look for the name and then create an if statement based on the value. so..
var x = readCookie('age');
if (x=='not13') {
document.getElementById('emailBox').innerHTML = "<style type=\"text/css\">.formError {display:none}</style><p>Good Bye</p><p>You must be 13 years of age to sign up.</p>";
}

Related

How to check if an element has a class using PHP in Wordpress function.php file

I am trying to hide an element on the front-end and remember the user choice by creating a cookie in PHP.
Here is how I have it set up:
I have some HTML and JS scripts inside an HTML widget on the page on the front-end
<div id="training-banner"> training banner design here </div>
<button onclick="myFunction()" id="close-btn">X</button>
<script>
function myFunction() {
var element = document.getElementById("training-alert");
element.classList.add("hidebanner");
}
</script>
Then I have written the cookie function inside the function.php of the child theme:
add_action('init', function() {
if (!isset($_COOKIE['training_banner_cookie'])) {
setcookie('training_banner_cookie', 'showbanner', strtotime('+1 day'));
}
if (class_exists('hidebanner')){
?><style>#training-alert{display:none;}</style> <?php
setcookie('training_banner_cookie', 'hidebanner', strtotime('+1 day'));
}
$cookieValue = $_COOKIE['training_banner_cookie'];
if ($cookieValue == "hidebanner"){
?><style>#training-alert{display:none;}</style> <?php
}
});
For some reason, the class_exists() PHP function does not work, any idea how this can be achieved?
https://www.php.net/manual/en/function.class-exists.php
class-exists is not used in your case. It is used to check if a Class exists in your PHP code block.
if (class_exists('MyClass')) {
$myclass = new MyClass();
}
What you want to do is to save the choice of the users' choice. You can simply use JS to achieve it.
<div id="training-banner"> training banner design here </div>
<button onclick="myFunction()" id="close-btn">X</button>
<script>
function getCookie(cookieName: string, cookie?: string): string {
const name = cookieName + '='
const decodedCookie = decodeURIComponent(cookie || document.cookie)
const ca = decodedCookie.split(';')
for (let i = 0; i < ca.length; i++) {
let 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 setCookie(
cookieName,
value,
days,
isSecure = true
): void {
let expires = ''
const secure = isSecure ? '; Secure' : ''
if (days) {
const date = new Date()
date.setTime(date.getTime() + days * 86400000)
expires = ' ;expires=' + date.toUTCString()
}
document.cookie = cookieName + '=' + value + expires + ' ;path=/' + secure
}
function myFunction() {
var element = document.getElementById("training-alert");
element.classList.add("hidebanner");
setCookie('training_banner_cookie_hide', true, 1)
}
function init(){
var shouldHideBanner = getCookie('training_banner_cookie_hide')
if(shouldHideBanner){
var element = document.getElementById("training-alert");
element.style.display = 'none';
}
}
init()
</script>
With the help of #WillyLi's answer, I was able to organize my thoughts and modify his code a bit here is what worked for me:
I modified the getCookie function declaration and simplified it to one parameter cname.
Then I also modified the setCookie and standardized it according to w3school
Finally, I wanted the banner to be hidden immediately as the user clicks the button so I added element.style.display = 'none'; to myFunction()
Here is what the final version looks like:
<button onclick="myFunction()" id="close-btn">X</button>
<script>
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for(let i = 0; i <ca.length; i++) {
let 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 setCookie(cname, cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
let expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function myFunction() {
var element = document.getElementById("training-alert");
element.style.display = 'none';
setCookie('training_banner_cookie_hide', true, 1);
}
function init(){
var shouldHideBanner = getCookie('training_banner_cookie_hide');
if(shouldHideBanner){
var element = document.getElementById("training-alert");
element.style.display = 'none';
}
}
init()
</script>

Javascript - Popup every time customer enters the store

I saw the age-verification snippet solution for my problem and it worked great. But in that solution the occurrence of that popup is based on the number of days. I want the popup to occur every time the user enters my website. How to do it?
Here's is the JS part of the snippet code.
<script>
function ageCheck() {
var min_age = {{ age }}; // Set the minimum age.
var year = parseInt(document.getElementById('byear').value);
var month = parseInt(document.getElementById('bmonth').value);
var day = parseInt(document.getElementById('bday').value);
var theirDate = new Date((year + min_age), month, day);
var today = new Date;
if ((today.getTime() - theirDate.getTime()) < 0) {
window.location = 'http://google.com'; //enter domain url where you would like the underaged visitor to be sent to.
} else {
var days = 1; //number of days until they must go through the age checker again.
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
document.cookie = 'isAnAdult=true;'+expires+"; path=/";
location.reload();
};
};
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;
};
var isAnAdult = readCookie('isAnAdult');
if (isAnAdult) {
document.write("<style> #prompt-background { display: none; }</style>");
};
</script>
and the button that function is called on
<button id="submit_birthdate" class="exitbutton" onclick="ageCheck()">Enter</button>
How to modify this code so that the popup appears every time?

JavaScript Compiler Error in Tag Manager

I'm trying to use a cookie to set user pageviews per session through GTM. I'm using a custom JavaScript variable:
function readCookie(name) {
var cookieName = name + "=";
var cookieSplit = document.cookie.split(';');
for (var i = 0; i < cookieSplit.length; i++) {
var cookies = cookieSplit[i];
while (cookies.charAt(0) === ' ') cookies = cookies.substring(1, cookies.length);
if (cookies.indexOf(cookieName) === 0) return cookies.substring(cookieName.length, cookies.length);
}
return null;
}
function viewAppend() {
var oldCookie = readCookie('viewCount');
if (oldCookie === null) {
document.cookie = "viewCount=1; path=/";
} else {
var views = oldCookie + 1;
document.cookie = "viewCount="+views+"; path=/";
}
}
viewAppend();
I keep getting the same Compiler error: "Error at line 12, character 1: Parse error. ')' expected."
I can't seem to figure out what I'm doing wrong, but any help is appreciated.
------ EDIT ------
Via my comment below, this is my current code. Current error is : "Error at line 16, character 40: Parse error. Semi-colon expected"
function doStuff() {
function readCookie(name) {
var cookieName = name + "=";
var cookieSplit = document.cookie.split(';');
for(var i=0;i < cookieSplit.length;i++) {
var cookies = cookieSplit[i];
while (cookies.charAt(0) === ' ') cookies = cookies.substring(1,cookies.length);
if (cookies.indexOf(cookieName) === 0) return cookies.substring(cookieName.length,cookies.length);
}
return null;
}
function viewAppend() {
var oldCookie = readCookie('viewCount');
if (oldCookie === null) {
document.cookie = "viewCount="1"; path=/";
} else {
var views = parseInt(oldCookie) + 1;
document.cookie = "viewCount="+views+"; path=/";
}
}
}
You have quoting problems on this line:
document.cookie = "viewCount="1"; path=/";
it should be:
document.cookie = "viewCount=1; path=/";
You don't need to put quotes around the value of a cookie (and if you did, you could either escape them or use single quotes around the whole string).
Alright, I went back to the drawing board and tried approaching the problem another way. At first I was trying to build everything into a single custom JavaScript variable in GTM. That was folly. I decided to approach it as such:
First, I built a custom HTML tag in GTM to read/write the PageView cookie that fired on all pages.
<script>
function readCookie(name) {
var cookieName = name + "=";
var cookieSplit = document.cookie.split(';');
for(var i=0;i < cookieSplit.length;i++) {
var cookies = cookieSplit[i];
while (cookies.charAt(0) === ' ') cookies = cookies.substring(1,cookies.length);
if (cookies.indexOf(cookieName) === 0) return cookies.substring(cookieName.length,cookies.length);
}
return null;
}
function viewAppend() {
var oldCookie = readCookie('viewCount');
if (oldCookie === null) {
document.cookie = "viewCount=1; path=/";
} else {
var views = parseInt(oldCookie) + 1;
document.cookie = "viewCount="+views+"; path=/";
}
}
viewAppend();
</script>
Then I built a custom Javascript variable that read the cookie and returned it as an integer.
function doStuff() {
function readCookie(name) {
var cookieName = name + "=";
var cookieSplit = document.cookie.split(';');
for(var i=0;i < cookieSplit.length;i++) {
var cookies = cookieSplit[i];
while (cookies.charAt(0) === ' ') cookies = cookies.substring(1,cookies.length);
if (cookies.indexOf(cookieName) === 0) return cookies.substring(cookieName.length,cookies.length);
}
return null;
}
var oldCookie = readCookie('viewCount');
var views = parseInt(oldCookie);
return views;
}
Then I simply built my pagievew tag that triggered whenever the pageviews variable was greater than 4 on Window Load to indicate an engaged user.
Thanks #Barmar for the help thinking about the problem. Your questions definitely challenged how I was approaching it.

Cookie jquery hide and show div

I wanna use my javascript cookie to let the application see if the user already loggedIn.. i get the value of the cookie in my console.. but whenever i make an statement and wanna hide a div the div doesn't do anything it doesn't show or hide.. can you guys please help me??
function writeCookie(name,value,days) {
var date, expires;
if (days) {
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 readCookie(name) {
var i, c, ca, nameEQ = name + "=";
ca = document.cookie.split(';');
for(i=0;i < ca.length;i++) {
c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(nameEQ) == 0) {
return c.substring(name.length,c.length);
}
}
return '';
}
var user = readCookie('email');
if (!user) {
document.getElementById('loginNav').style.display = 'block';
document.getElementById('username').style.display = 'block';
$("#loginNav").css("display","block");
}else{
$("#loginNav").css("display","block");
console.log( $("#loginNav").css("display","block"));
}
if $('#loginNav').length == 0 then your element has not been loaded yet.
Ensure that this code comes after your jquery link and it is surrounded by a :
$(document).ready(function(){
var user = readCookie('email');
if (!user) {
$('#loginNav, #username').show();
}else{
$("#loginNav, #username").hide();
//did you forget to hide the username?
}
});
Make sure you load all your JS files at the end of your HTML age.
Hi set the "display" property to "none" to hide.... and "block" to show
I would also use "visibility":
if (!user) {
$("#loginNav, #username").css("display","block");
$("#username, #username").css("visibility","visible");
}else{
$("#loginNav, #username").css("display","none");
$("#username, #username").css("visibility","hidden");
}

Javascript - Using cookies to store an integer

I am trying to use a cookie to store a single integer, so when the user refreshes the page I am able to retrieve the previous number they were on (in an attempt to stop doubles of a video appearing).
What would the minimum requirements be to accomplish this?
var randomNumber = Math.floor((Math.random()*10)+1);
document.cookie=(randomNumber);
Setting a cookie:
document.cookie = 'mycookie=' + randomNumber + ";max-age=" + (300) + ";";
Reading a cookie:
var cookie = document.cookie;
alert(decodeURIComponent(cookie));
The cookie contains some other random stuff like push=1 as well as mycookie. Should I be setting the cookie to null before I add the randomNumber?
As far as getting the value of mycookie would I just assign the cookie to a string and parse mycookie from it?
Tamil's comment is solid. Use these quirksmode functions if you ever wish to surpass minimal cookie usage:
cookie_create = function (name,value,days) {
var expires, date;
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
expires = date = null;
};
cookie_read = function (name) {
var nameEQ = name + "=",
ca = document.cookie.split(';'),
len = ca.length,
i, c;
for(i = 0; i < len; ++i) {
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);
}
nameEQ = name = ca = i = c = len = null;
return null;
};
cookie_erase = function (name){
cookie_create(name,"",-1);
name = null;
};
You could use document.cookie to read/write cookies in javascript:
document.cookie = 'mycookie=' + randomNumber + '; path=/';
And if you wanted the cookie to be persistent even after the user closing his browser you could specify an expires date.

Categories

Resources