hiding div javascript (vanilla) cookie - javascript

I'm trying to hide a div with javascript and store that information for the rest of the session. Closing the div isnt a problem but somehow the information isnt stored in my cookie.. this is what i have so far.
var p = document.getElementById ('pcontainer');
window.onload = function () {
if(document.cookie.length != 0){
var nameValueArray = document.cookie.split("=");
p.style.display = nameValueArray[1];
}
}
function popup(){
if(p.style.display != 'none'){
var none = 'none';
p.style.display = none;
document.cookie = "geenpopup=" + none;}
}

To set a cookie, you can use document.cookie = "name=value";, but to retrieve a cookie, you should do something like splitting the cookie by semi-colons, then find your variable name in the array of values. Something like this function:
function getCookie (name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
This function copied (and translated to vanilla JS) from Django docs.
So in your case, you could get the value with getCookie('geenpopup') [sic];

Related

Delete specific cookie with Javascript

I need to delete a specific cookie from a website. At first I have tried several ways to delete ALL cookies, however none of them worked properly (not all cookies were deleted).
I also tried the below code to find the cookie I need to delete, but I can't figure out how to delete it after found it.
Can anyone help?
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else
{
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
return decodeURI(dc.substring(begin + prefix.length, end));
}
function deleteCookie() {
var myCookie = getCookie("dropin_date");
if (myCookie == null) {
}
else {
// if cookie exists delete it
}
}
deleteCookie();
check this out.
function accessCookie(cookieName) {
var name = cookieName + "=";
var allCookieArray = document.cookie.split(';');
for(var i=0; i<allCookieArray.length; i++)
{
var temp = allCookieArray[i].trim();
if (temp.indexOf(name)==0)
return temp.substring(name.length,temp.length);
}
return "";
}
var delete_cookie = function(name) {
document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};
var mycookie = accesCookie('test');
if(mycookie != ''){
delete_cookie('test');
}
In order to delete a cookie set the expires date in the past. it will delete automatically

Fire remember me cookie only when user clicks checkbox

Updated Code: thank you for the suggestions so far. Still not working.
I'm trying to add a remember me cookie, but only when the user actually clicks the checkbox. Is this possible? I'm not having any luck with this code. The cookie fires regardless if the checkbox is clicked or not:
JavaScript:
<script>
$('#rememberme').click(function() {
if ($('#rememberme').is(':checked')) {
document.cookie="rememberme=yes;domain=.abc.com;path=/"
localStorage.usrname = $('#username').val();
localStorage.pass = $('#password').val(); localStorage.chkbx = $('#rememberme').val();
}
else {
document.cookie="rememberme=no;domain=.abc.com;path=/"
localStorage.usrname = '';
localStorage.pass = '';
localStorage.chkbx = '';
}
});
</script>
HTML:
<label class="checkbox" style="border: none;">
<input type="checkbox" value="rememberme" id="rememberme"> Remember me
</label>
Updated Code
$('#rememberme').click(function() {
if ($('#rememberme').is(':checked')){
document.cookie = "rememberme=yes;domain=.abc.com;path=/"
// save username and password
localStorage.usrname = $('#username').val(); localStorage.pass = $('#pass').val(); localStorage.chkbx = $('#rememberme').val();
}
else {
document.cookie = "rememberme=no;domain=.abc.com;path=/"
localStorage.usrname = '';
localStorage.pass = '';
localStorage.chkbx = '';
}
});
tested below code in jsfiddle, hope it works as per your need. Please test it once, and let me know if its working as expected.
https://jsfiddle.net/arivua/xpvt214o/924480/
// set cookie value
function setCookie(key, value) {
document.cookie = key +"="+ escape(value) +
";domain="+ window.location.hostname +
";path=/";
}
// delete cookie
function deleteCookie(name) {
setCookie(name, "");
}
var remember_me_check_box = $("#rememberme")
// handle click and manage cookie
remember_me_check_box.on("click", function(){
if (remember_me_check_box.is(':checked')) {
deleteCookie('rememberme');
setCookie('rememberme', 'yes');
} else {
deleteCookie('rememberme');
setCookie('rememberme', 'no');
}
})
The solution was to just set "If" and "else" conditions around the URL that declares rememeberme. However the conditional URL is constructed (notice yes vs no) is handled by the back end folks where I am a front end UI developer.
<script>
$('#rememberme').click(function() {
if ($('#rememberme').is(':checked')) {
document.cookie="rememberme=yes;domain=.abc.com;path=/";
}
else {
document.cookie="rememberme=no;domain=.abc.com;path=/";
}
});
$('#rememberme').click(function () {
if ($('#rememberme').is(':checked')) {
document.cookie = "rememberme=yes;path=http://localhost:3000/login/"
var u = document.getElementById('email').value;
var p = document.getElementById('password').value;
var r = document.getElementById('rememberme').value;
document.cookie = "email=" + u + ";path=http://localhost:3000/login/";
document.cookie = "password=" + p + ";path=http://localhost:3000/login/";
}
else {
document.cookie = "rememberme=no;path=http://localhost:3000/login/"
document.cookie = "email=;path=http://localhost:3000/login/";
document.cookie = "password=;path=http://localhost:3000/login/";
}
});
function getcookiedata() {
var user = getCookie('email');
var pswd = getCookie('password');
var remember = getCookie('rememberme');
document.getElementById('email').value = user;
document.getElementById('password').value = pswd;
if (remember == 'yes') {
document.getElementById('rememberme').checked = true;
} else {
document.getElementById('rememberme').checked = false;
}
}
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 "";
}
<input type="checkbox" name="rememberme" id="rememberme">&nbsp Remember Me<br>

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.

How to set a cookie that prevents further javascript alerts?

I have this code for detecting android:
var mobile = (/android/i.test(navigator.userAgent.toLowerCase()));
if (mobile){
alert("Message to android users");
}
...but how do I get that script to also set a cookie so the android user doesn't continue getting the alert (either on reloading the page, returning later to the page, or navigating to other pages which have the alert)?
I also have this, which uses a cookie to avoid a user viewing a "welcome page" they've already seen:
var RedirectURL = "http://www.example.com/real-home-page.html";
var DaysToLive = "365";
var CookieName = "FirstVisit";
function Action() {
location.href = RedirectURL;
}
DaysToLive = parseInt(DaysToLive);
var Value = 'bypass page next time';
function GetCookie() {
var cookiecontent = '';
if(document.cookie.length > 0) {
var cookiename = CookieName + '=';
var cookiebegin = document.cookie.indexOf(cookiename);
var cookieend = 0;
if(cookiebegin > -1) {
cookiebegin += cookiename.length;
cookieend = document.cookie.indexOf(";",cookiebegin);
if(cookieend < cookiebegin) { cookieend = document.cookie.length; }
cookiecontent = document.cookie.substring(cookiebegin,cookieend);
}
}
if(cookiecontent.length > 0) { return true; }
return false;
}
function SetCookie() {
var exp = '';
if(DaysToLive > 0) {
var now = new Date();
then = now.getTime() + (DaysToLive * 24 * 60 * 60 * 1000);
now.setTime(then);
exp = '; expires=' + now.toGMTString();
}
document.cookie = CookieName + '=' + Value + exp;
return true;
}
if(GetCookie() == true) { Action(); }
SetCookie();
Can the second script be adapted and combined into the first to do something like:
function Action() {
don't-open-that-alert-again;
I've googled and found some js cookie scripts, but all over 100K. Prefer something as succinct as the above.

Cookie only working without the www in front of my domain

I am setting a cookie in a disclaimer php file like this...
<script language = "JavaScript">
<!-- Begin hiding
function getCookieExpireDate(noDays){
var today = new Date()
var expr = new Date(today.getTime()+noDays*24*60*60*1000*365)
return expr.toGMTString()
}
function makeCookie(name, data, noDays){
var cookieStr = name + "="+ data
if (makeCookie.arguments.length > 2){
cookieStr += "; expires=" + getCookieExpireDate(noDays)
}
document.cookie = cookieStr
var hello="agreedterms.html";
window.location=hello;
}
function noway(){
var goodbye="index.html";
window.location=goodbye;
}
// End hiding -->
</script>
And then checking for it in index php like this....
<script language = "JavaScript">
function getCookieVal (offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1) {
endstr = document.cookie.length;
}
return unescape(document.cookie.substring(offset, endstr));
}
function getCookie (cookieName) {
var arg = cookieName + "=";
var argLength = arg.length;
var cookieLength = document.cookie.length;
var i = 0;
while (i < cookieLength) {
var j = i + argLength;
if (document.cookie.substring(i, j) == arg) {
return getCookieVal(j)
}
if (i == 0) {
break
}
}
return null;
}
if(getCookie('disclaimer') == null) {
location.href="disclaimer.php"
}
</script>
This all works fine if I access the site using mydomain.com - but if I use www.mydomain.com then it doesn't work.
Any ideas what I am doing wrong? Do I need to include the www somehow?
If I remeber you have to set the domain and path for the cookie by appending following to your cookie string
;domain=.domain.com;path=/
Where obviously you replace the domain by your domain. The . in front of the domain name makes it valid for all subdomains following the domain you are currently on.
Edit:
See also the following Stack Overflow answer: Creating a javascript cookie on a domain and reading it across sub domains

Categories

Resources