Show a div if a cookie exists - javascript

So... I've been trying to show an element for recurrent visitors to my site.
This is how I'm trying to do it: (you can see this JSfiddle as well)
$(document).ready(function() {
// If the 'show cookie is set we show the message
if (!readCookie('show')) {
$('#hide').show();
}
else {
$("#hide").hide();
createCookie("show", true, 1);
}
return false;
});
And I'm also using this cookie functions that I took from w3schools
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);
}
However, it's not working and I'm pretty sure it has something to do with my JQuery attempt, just not sure where my mistake is.
Thanks for any help!
---Edit Update---
Following some advices, this is what I've got now:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie#2/src/js.cookie.min.js"></script>
<script>
$(function(){
if(Cookies.get('previsitor')) {
$('#atc').show(1000);
}
});
</script>
</head>
<body>
<div id="atc" style="display: none">
Something I want to hide
</div>
<script>
Cookies.set ("previsitor","true",{ expires: 1 });
alert(document.cookie);
</script>
</body>
</html>
I'm using this library for my cookie management: https://github.com/js-cookie/js-cookie
However, it's still not doing what I want, I'm usin the alert(document.cookie); and looks like the cookie is not being created at all... but why!? :(

Try this. This should do the trick.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>
<script type="text/javascript">
//pass cookie name
if(checkCookie('the_cookies')){
$('#atc').show();
}
else{
$('#atc').hide();
}
function checkCookie($name)
{
if (typeof $.cookie($name) === 'undefined'){
// set cookie if not exists
$.cookie($name, 'the_value');
return false;
} else {
return true;
}
}
</script>

You just need to create your cookie after the if/else block
$(document).ready(function() {
// If the 'show cookie is set we show the message
if (!readCookie('show')) {
$('#hide').show();
}
else {
$("#hide").hide();
}
createCookie("show", true, 1);
});
Previously, the createCookie function wasn't being called at all since it was nested in the false condition.

Change calling
if (readCookie('show')) {
$('#hide').show();
}
else {
$("#hide").hide();
createCookie("show", true, 1);
}
return false;
});
Change this function
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)
{alert(nameEQ.length,c.length);
return c.substring(nameEQ.length,c.length);}
}
return false;
}
This should work!

Related

Get browser cookies

I'm trying to get the browser cookies using:
browser.cookies.getAll() but I always get this error in the console log instead:
Uncaught ReferenceError: browser is not defined
here's my code:
var gettingAll = browser.cookies.getAll({
url: "url"
});
console.log(gettingAll);
to get the url value u can use this solution :
var cookiesMap = document.cookie.split(";").map( value => {
var val =value.split("=")
var obj = { "key" : val[0], "value" : val[1] }
return obj;
});
for( var i = 0 ; i < cookiesMap.length ; i++ ){
if( cookiesMap[i].key==="url"){
console.log(cookiesMap[i].value);
}
}
hope it helps :)
Have a look at the following...
https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
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 "";
}
Edit: fixed code block.
browser is indeed undefined. It's not a native JavaScript object.
You should use document.cookie (see here) instead.

Cookie is not deleting properly using jquery

I have a task to set the cookie for the menu.I have a horizontal menu.When I click on the menu the id of the menu is set in to the cookie.But when I am selecting the next menu cookie shows the first input value.For that I used $.removeCookie("activeDivId");.But it doesn't work properly.How can I solve this problem?
Html code is
<div class="menuBar">
<div id="divHome" class="menuHeader ui-corner-top">
<span>Home</span>
</div>
<div id="divNewTransaction" class="menuHeader ui-corner-top">
<span><a href="#" onclick="NewTransaction()" >New Transaction</a></span>
</div>
</div>
javascript file is
$(document).ready(function () {
$(".menuHeader").click(function () {
$.removeCookie("activeDivId");
$.cookie("activeDivId", this.id); });
alert(document.cookie);
var activeDivId = $.cookie("activeDivId") ? $.cookie("activeDivId") : "divHome";
$("#" + activeDivId).addClass("menuHeaderActive");
});
$(document).ready(function () {
//for debugging purpose, so that you can see what is in the menu cookie
$('#debug').html('Cookie Content : ' + readCookie('menu'));
//if cookie menu exists
if (readCookie('menu')) {
//loop through the menu item
$('#menu a').each(function () {
//match the correct link and add selected class to it
if ($(this).html() == readCookie('menu')) $(this).addClass('selected');
});
}
$('#menu a').click(function () {
//Set the cookie according to the text in the link
createCookie('menu', $(this).html(),1);
});
});
/* Cookie Function */
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);
}
You Can Use this method instead of jquery Method
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 = "";
//var fixedName = '';
/// name =name;
document.cookie = name + "=" + value + expires + "; path=/";
this[name] = value;
}
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 c;
}
function eraseCookie(cookiename) {
this.createCookie(cookiename, '', -1);
this[cookiename] = undefined;
// Ecookie(cookiename);
}

Calling functions correctly in premade javascript

I got this HTML code:
<head>
<link href="default.css" title="default" rel="stylesheet" type="text/css" />
<link href="theme1.css" title="theme1" rel="stylesheet" type="text/css" />
<link href="theme2.css" title="theme2" rel="stylesheet" type="text/css" />
<link href="theme3.css" title="theme3" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="javascript.js"></script>
</head>
<body>
<ul id="dropdown">
<li> Choose theme
<ul>
<li id="stylesheet1" > Default </li>
<li id="stylesheet2" > Theme 1 </li>
<li id="stylesheet3" > Theme 2 </li>
<li id="stylesheet4" > Theme 3 </li>
</ul>
</li>
</ul>
</body>
And I got this is the code in the separate file javascript.js:
function setActiveStyleSheet(title) {
var i, a, main;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
a.disabled = true;
if(a.getAttribute("title") == title) a.disabled = false;
}
}
}
function getActiveStyleSheet() {
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 getPreferredStyleSheet() {
var i, a;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1
&& a.getAttribute("rel").indexOf("alt") == -1
&& a.getAttribute("title")
) return a.getAttribute("title");
}
return null;
}
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("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
}
window.onunload = function(e) {
var title = getActiveStyleSheet();
createCookie("style", title, 365);
}
var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
// Last part
function initate()
{
var style1 = document.getElementById("stylesheet1");
var style2 = document.getElementById("stylesheet2");
var style3 = document.getElementById("stylesheet3");
var style4 = document.getElementById("stylesheet4");
style1.onclick = function () {
setActiveStyleSheet("default");
return false;
};
style2.onclick = function () {
setActiveStyleSheet("theme1");
return false;
};
style3.onclick = function () {
setActiveStyleSheet("theme2");
return false
};
style4.onclick = function () {
setActiveStyleSheet("theme3");
return false
};
}
window.onload = initate;
I'm new to javascripts and I haven't written this script myself (http://www.alistapart.com/articles/alternate/) and I managed to create the last part (as shown by comment in code) by myself to have the eventhandlers separate in the javascript file as I want and this part enables the style sheets to be changed the way I want it. But I can't figure out how to get the cookies to work as well to get the themes I'm using to be saved.
EDIT:
Since I'm new I still have a hard time figuring this code out but I've tried changing the last function initiate and used onClick eventhandlers for the saving of cookies but I can't get it to work.
I've used this:
style1.onclick = function () {
createcookie(T1, style, 7);
}
And
document.getElementById("stylesheet1").onclick(createCookie(T1, style, 7));
And when I did the changing of style sheets didn't work anymore.
This works:
style1.onclick = function () {
createcookie(T1, style, 7);
}
because what you do is you set the onclick handler to a function. You don't call the function there, you just give it away so that someone else (the browser) can call it.
This doesn't work:
document.getElementById("stylesheet1").onclick(createCookie(T1, style, 7));
because you call the function right there. What you do is:
Invoke createCookie with 3 parameters
Invoke onclick with the return value from createCookie
What you want is probably something like:
document.getElementById("stylesheet1").onclick = function() {
createCookie(T1, style, 7);
};
what this does, is create an anonymous function and sets this function to the onclick property of the element. This anonymous function, when called, will call the createCookie function.
The reason you need to do this, is because you have parameters to createCookie, and those parameters must be bound somewhere until it's time to call the function.

remember cookie

i want to make a cokkie which can save my selected region on netsoltech.com whenever user select the region on map it can save the cookie and when the next time user come on domain the automatic go to 1st time click region page i make this code
but the problem is when the user come on next time then 1st region selector page come then it can refresh and go to the region page.. not the automatic...
<script>
/*
Cookie script - Scott Andrew
Popup script, Copyright 2005, Sandeep Gangadharan
*/
function newCookie(name,value,days) {
var days = 10; // the number at the left reflects the number of days for the cookie to last
// modify it according to your needs
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 nameSG = name + "=";
var nuller = '';
if (document.cookie.indexOf(nameSG) == -1)
return nuller;
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(nameSG) == 0) return c.substring(nameSG.length,c.length); }
return null; }
function eraseCookie(name) {
newCookie(name,"",1); }
function toMem(region) {
newCookie('region', region);
window.location= "http://www.netsoltech.com/"+region+"/index";
}
function remCookie() {
window.location= "http://www.netsoltech.com/"+readCookie("region")+"/index";
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function() {
remCookie();
});
</script>
Try this
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
//redirect here
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function checkCookie() {
var region = getCookie("region");
if (region != null && region != "") {
alert("redirect to " + region); //replace this with redirect
}
}
checkCookie(); //check this on page load
and the HTML
europe
JSFiddle
http://jsfiddle.net/YtF2B/6/

How to create Cookies with jQuery?

How to set cookies for this script?
<script type="text/javascript">
$(document).ready(function(){
$("a.switch_thumb").toggle(function(){
$(this).addClass("swap");
$("ul.display").fadeOut("fast", function() {
$(this).fadeIn("fast").addClass("thumb_view");
});
}, function () {
$(this).removeClass("swap");
$("ul.display").fadeOut("fast", function() {
$(this).fadeIn("fast").removeClass("thumb_view");
});
});
});
</script>
You don't need jQuery for this (though there there are several $.cookie plugins). You can just use the three cross-browser functions found on quirksmode:
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);
}

Categories

Resources