create and save cookies on onclick - javascript

Can anyone help me set up a cookie function that can take user input by checking which link the user clicked on and then redirect them to that link and create a cookie for it so the next time the user comes they automatically get redirected.
Can anyone please tell me what am I doing wrong. I want multiple links and clicking on each link should create a cookie and redirect the user.
Can anyone provide a working jsFiddle please.
The code is below please help:
//Html
something site
something2 site
// Javascript
function redirectOne(state)
{
createCookie('state', state, 90);
window.location.href = "www.something1.com" + state;
}
function redirectTwo(state)
{
createCookie('state', state, 90);
window.location.href = "www.something2.com" + state;
}
var cookie = readCookie('state');
if (cookie != null)
{
window.location.href = "www.something.com" + cookie;
}
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);
}

Your problem is that when you call this line in each function
createCookie('state', state, 90);
It's taking the value of '/home' from the onClick event and passing it to the cookie creation routine. You should be passing in something other than '/home' for both functions.
something site
something2 site
// Javascript
function redirectOne(state)
{
createCookie('state', state, 90);
window.location.href = state+'/home';
}
You do not need the redirectTwo function at all.

Related

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.

Language switcher - Javascript/jQuery and Cookies

Using both internet and Stack Overflow resources I managed to write a crude HTML website, that allows the user to switch Language of it on the fly, using Javascript, jQuery and XML.
Now, the problem I ran into is to keep the preferred language across the entire portal, without the need to change it each time when navigating through it. I have decided to use a simple cookie to keep the track of it, but it seems I have messed something up, and I can't figure out what I'm doing wrong.
Basically speaking, the page itself has text in the code itself (as a backup just in case), however the text becomes invisible when booting the site, until I switch a language, nor the language is kept when I navigate the portal. For the former, I assumed that the script was reading some empty or overall wrong cookie, so I made an attempt to filter it out and use a default language, but in vain. As for the latter issue, I guess I save the cookie itself wrong as well, but I can't seem to figure out what's wrong with it.
Any help/advice would be appreciated.
function changeLanguage(lang) {
$(function() {
$.ajax({
url: 'jezyki.xml',
success: function(xml) {
$(xml).find('translation').each(function(){
var id = $(this).attr('id');
var text = $(this).find(lang).text();
$("." + id).html(text);
if (lang === "") { }
else {
var title = lang;
createCookie("language", title, 365);
}
});
}
});
});
}
$(document).ready(function () {
$("input[name='radio-language']").click(function () {
changeLanguage($(this).val());
});
});
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 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;
}
window.onload = function (e) {
var cookie = readCookie("language");
var domyslny = "english";
if (title === "") { changeLanguage(domyslny); } else { changeLanguage(title); }
}
Apologies if this is something silly, I am quite a newbie when it comes to Javascript/jQuery.

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

Clear all cookie using Javascript

Is there anyway to clear the cookie using javascript?
First, I need to clearify the problem. Many posts in StackOverflow give this kind of answer. But it is clearing cookie like setting the value of all the keys to empty string. But I need to erase the keys as well. How can I do that?
PS: I tried document.cookie = null, but it does not work here
The best way I found is to expire the cookie you want to delete, use this javascript:
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);
}

Cookie value to define style on page load

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

Categories

Resources