Why js cookie being written only if I click button two times? - javascript

I have a button that should write a cookie once it's clicked and change button's textContent
<button id="menu-icon" onclick="writeCookie()">volume_up</button>
But it would write cookie only if I click it two times.
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 writeCookie(){
let element = document.querySelector("#menu-icon")
let state = element.textContent;
switch(state) {
case 'volume_off':
element.textContent = 'volume_up'
createCookie("default", "", -1)
createCookie("default", true, 100)
break;
case 'volume_up':
element.textContent = 'volume_off'
createCookie("default", "", -1)
createCookie("default", false, 100)
break;
}
}
How can I fix it?

Remove the onclick="writeCookie() from the html and add the following line in the js file.
document.document.getElementById("menu-icon").addEventListener("click", writeCookie);
You should also check the console log.

This can happen because your page is not fully loaded or element wrongly initialized.
If you are using jquery try on() method
<button id="menu-icon" >volume_up</button>
<script>
$(document).ready(function(){
$("#menu-icon").on("click",function(){
writeCookie();
});
});
</script>

Related

Script to change cookie expiration to 6 months

I'm definitely new to Javascript, but I need to implement a tag within GTM to update 2 cookie values to 6 months for any unique user after the are loaded on the page.
I have the following script to alter the expiration date:
<script>
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2)
return parts.pop().split(";").shift();
}
var date = new Date();
date.setTime(date.getTime()+(365*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
console.log("expires: " + expires);
var cookieName = "CookieA";
var OABCcookieName = "CookieB";
function updateCookieExpiration() {
var cookie = getCookie(cookieName);
document.cookie = cookieName + "=" + cookie + expires + ";path=/; Samesite=Lax;" //domain=" + domain + ";";
var OABCcookie = getCookie(OABCcookieName);
document.cookie = OABCcookieName + "=" + OABCcookie + expires + ";path=/; Samesite=Lax;" //domain=" + domain + ";";
}
</script>
My question is, if I add the following script, update 365 to 180, and call the updateCookieExpiration() function - won't the function be called on every page and cause the cookie expiration to always reset to 6 months?
If so, is there additional logic that I need to add to make sure the cookie expiration hasn't already been reset for a unique visitor, to avoid the scenario described?
Any help troubleshooting would be great and very appreciated!
You could add a condition check if the Cookie name already exist:
// You may prefer using max-age here
const sixMonthMaxAge = 60 * 60 * 24 * 180;
var newCookieName = "CookieA";
function updateCookieExpiration() {
const cookie = getCookie(cookieName);
// If cookie doesn't exist
if(!cookie) {
document.cookie = cookieName + "=" + cookie + ";" + "max-age=" sixMonthMaxAge + ";"
}
}
Using js-cookie library
Using library that abstract Cookie management can be a good idea, even more if you have to manager multiple cookies.
import Cookies from 'js-cookie'
const sixMonthMaxAge = 180; // You can provide the max-age in days
var newCookieName = "CookieA";
function updateCookieExpiration() {
const cookie = Cookies.get(cookieName);
if(!cookie) {
Cookie.set(cookieName, 'your_value', { expires: sixMonthMaxAge })
}
}
Cookies.set('foo', 'bar')

Live Cookie Checker in js

I'm working on a solution that checks the cookies in real time.
Once you have opened a link, a cookie is created. This cookie should be checked in real time and depending on the content, the corresponding text (send button) should be displayed.
The code works. Where I have the problem is with the IF sequence, which should be checked again and again without reloading the page.
<script language="JavaScript" type="text/javascript">
function SetCookie(cname, cvalue) {
var d = new Date();
d.setTime(d.getTime() + (3560*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires;
};
function getCookieValue(a) {
var b = document.cookie.match('(^|;)\\s*' + a + '\\s*=\\s*([^;]+)');
return b ? b.pop() : '';
};
</script>
<img src="bilder/icon.png" height="75">
<script language="JavaScript" type="text/javascript">
if (getCookieValue("klickonbutton") == 'ja') {
document.write ('<input type="submit" value="Senden" id="senden">');
} else {
document.write ('<p><b><font color="#FF0000">Error Message</b></font></p>');
document.write ('<input type="submit" value="Senden" id="senden" disabled="disabled">');
};
</script>
document.write deletes the entire HTML and adds the Html which you specify in the parameter. Instead what you should do is add the button and error div on the HTML and toggle the display of these based on the cookie value. Check out the sample code.
<img src="bilder/icon.png" height="75">
<input type="submit" value="Senden" id="senden">
<p style="display: none" id="error"><b><font color="#FF0000">Error Message</b></font></p>
<script language="JavaScript" type="text/javascript">
function SetCookie(cname, cvalue) {
var d = new Date();
d.setTime(d.getTime() + (3560*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires;
checkIsCookieAvailable();
};
function getCookieValue(a) {
var b = document.cookie.match('(^|;)\\s*' + a + '\\s*=\\s*([^;]+)');
return b ? b.pop() : '';
};
function checkIsCookieAvailable() {
const senden = document.querySelector('#senden');
const error = document.querySelector('#error');
setInterval(() => {
if (getCookieValue("klickonbutton") == 'ja') {
senden.style.display = 'block';
senden.disabled = false;
error.style.display = 'none';
} else {
error.style.display = 'block';
senden.disabled = true;
}
}, 1000)
}
</script>

Creating and Checking cookies value with javascript/jquery

I'm setting up a new pop up and would like to create cookie. The basic function is to add classes into the wrapper if a cookie exists (or depending on value if that's possible). This is what I got so far:
HTML:
<div id="new-popup" class="active ">
<span class="collapse-popup">X</span>
<form>
<input class="tnp-email" type="email" placeholder="Email Address" name="ne" required="">
<input class="tnp-submit" type="submit" value="Submit">
</form>
</div>
JS/JQUERY:
jQuery(document).ready(function($) {
var popuptwo = $('#new-popup');
var cookie = GetCookie("testbb2020");
if(cookie == null) { }
if(cookie === 'closed') {
$('#new-popup').addClass('closed-test')
}
if(cookie === 'subscribed') {
$('#new-popup').addClass('subscribed-test')
}
// Click on "Close"
$('#new-popup .collapse-popup').click(function(event) {
var date = new Date();
date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
document.cookie = "testbb2020=closed" + expires + "; path=/"; {
}
});
// Click on "Subscribe"
$('#new-popup input.tnp-submit').click(function(event) {
var date = new Date();
date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
document.cookie = "testbb2020=subscribed" + expires + "; path=/"; {
}
});
});
JQuery no longer has an active plugin for this. Two alternatives exist depending on your needs:
you can use JS-Cookie for a way to work with cookies in Javascript
you can use LocalStorage instead of cookies
LocalStorage is the easier way, but if you need compatibility with older browsers go with cookies.

Cannot set cookie to expire on browser close

I'm trying to set a cookie using javascript so it expires when the browser is closed.
I have the following function to do that:
function createCookie(value,days) {
var name = "name";
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
var cookie = name + "=" + value + expires + "; path=/";
document.cookie = cookie;
}
I tried many ways found here and there on the web like setting the date to "", setting it to yesterday (in that case the cookie is not even added) and omitting "expires" completly. I tried on Firefox and Chrome checking that every process was stopped before opening again, but the cookie is alway there.
What am I missing?
I am using this function for my self. It will work for you i gess :)
function createCookie(name, value, expiresInX_days, path) {
var a = new Date;
var expires = expiresInX_days || 1;
a.setTime(Date.now() + (1000 * 60 * 60 * 24 * expires));
var pt = path ? " ; path=" + path + ";" : ";";
return (document.cookie = name + "=" + value + ";" + "expires=" + a.toUTCString() + pt) ? !0 : !1;
}
If you want to delete your cookie, you can use this:
function rmCookie(cookieName){
var a = new Date;
a.setTime(0);
return (document.cookie = cookieName + "=;" + a.toUTCString()) ? !0 : !1;
}
If you want get your cookie clean,
function getMyFuckingCookie(cookieName){
var a = document.cookie.replace(/; /g, ";").split(";"),
b = a.length,
c = {},
nm = cookieName || !1;
while (b--) {
var d = a[b].split(/=(.+)/);
c[d[0]] = d[1];
}
return (nm) ? c[nm] : c;
}

How to delete the cookie at time of reloading the page?

I have one requirement, at the time of pageloading I'm setting cookie using sessionStorage, once refresh/reload the page I have to delete the cookie.
I tried with the following code, but cookie is not deleting for reload the page,
Can someone help me please,
$(document).ready(function() {
$('#example').dataTable({
"bStateSave": true,
"fnStateSave": function (oSettings, oData) {
sessionStorage.setItem('POSummary', JSON.stringify(oData));
},
"fnStateLoad": function (oSettings) {
return JSON.parse(sessionStorage.getItem('POSummary'));
}
});
} );
Thanks
if you want delete a sessionStorage element you need to do this:
sessionStorage.removeItem("session-name");
if(sessionStorage.getItem('POSummary') != null)
sessionStorage.removeItem("POSummary");
if you want use cookie instead you must implement this two function:
function create (name, value, days){
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
} else {
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
function erase (name){
create(name, "", -1);
}

Categories

Resources