Creating and Checking cookies value with javascript/jquery - javascript

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.

Related

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

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>

Uncaught TypeError: Cannot read property cookie

I finally get the code to work after a search online I get the right solution to it at Setting cookies with form input
the code works but the value submitted are not what i expect.
it store this value="Submit!" but i want to store the value submited
How do i get the value submited
var today = new Date();
var expiry = new Date(today.getTime() + 30 * 24 * 3600 * 1000); // plus 30 days
function setCookie(name, value) {
document.cookie = name + "=" + escape(value) + "; path=/; expires=" + expiry.toGMTString();
}
function putCookie(form) {
alert("Hash send sucessfull");
setCookie("hashvalue", form.hashform.value);
return true;
}
function storeValues(form) {
setCookie("hashvalue", form.submit.value);
return true;
}
<form name='hashform' onsubmit="storeValues(this)">
<input type="text" value="Enter Your hash to mine" id="usrname">
<input type="submit" value="Submit!" id="submit">
</form>
In fact last error was the name of the form in the line:
setCookie("hashvalue", form.hashsandbox.value);
i haved form.submit.value and need to have the name of the field
Here is the full working code
var today = new Date();
var expiry = new Date(today.getTime() + 30 * 24 * 3600 * 1000); // plus 30 days
function setCookie(name, value) {
document.cookie = name + "=" + escape(value) + "; path=/; expires=" + expiry.toGMTString();
}
function storeValues(form) {
setCookie("hashvalue", form.hashsandbox.value);
alert("Hash send sucessfull");
return true;
}
<form name='hashform' onsubmit="storeValues(this)">
<input type="text" value="Enter Your hash to mine" id="hashsandbox">
<input type="submit" value="Submit!" id="submit">
</form>

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')

textarea + jquery proble

I made some scripts in JS and connected it to html.
These two pieces of code are the same, but for textarea "name" works and for textarea "about" don't. Please help me!
HTML (it isn't the whole document):
<div>
Назва:
<textarea type="text" class="form-control" class="name" id="name"></textarea>
<span class="namme"></span>
</div>
<div>
Опис товару:
<textarea type="text" class="form-control" class='about' id='about'></textarea>
<span class="abbout"></span>
</div>
JS:
jQuery(document).ready(function($){
$("#name").change(function(){
var name1 = $("textarea#name").val();
$(this).next('.namme').text("Запам'ятовано");
createCookie("namme", name1, "1");
});
$('.name').trigger('change');
$('#about').change(function(){
var about1 = $('#about').val();
$(this).next('.abbout').text("Запам'ятовано");
createCookie("abbout", about1, "1");
});
$('.about').trigger('change');
});
function createCookie(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 = encodeURIComponent(name) + "=" +
encodeURIComponent(value) + expires + "; path=/";
}
Well, on my browser your code as is works fine for both textareas, see below snippet:
jQuery(document).ready(function($){
$("#name").change(function(){
var name1 = $("textarea#name").val();
$(this).next('.namme').text("Запам'ятовано");
createCookie("namme", name1, "1");
});
$('.name').trigger('change');
$('#about').change(function(){
var about1 = $('#about').val();
$(this).next('.abbout').text("Запам'ятовано");
createCookie("abbout", about1, "1");
});
$('.about').trigger('change');
});
function createCookie(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 = encodeURIComponent(name) + "=" +
encodeURIComponent(value) + expires + "; path=/";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
Назва:
<textarea type="text" class="form-control" class="name" id="name"></textarea>
<span class="namme"></span>
</div>
<div>
Опис товару:
<textarea type="text" class="form-control" class='about' id='about'></textarea>
<span class="abbout"></span>
</div>

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