jQuery cookie expiring every page - javascript

Trying to create a cookie policy where when the button is click, it doesn't display for 30 days, however when the button is clicked it shows again if you refresh the page or change page.
code is below:
obviously I've added in jQuery at the bottom of the page
<div class="cookie-message" id="cookie_banner">
<div class="container">
<h3>This site uses cookies</h3>
<br>
<p>We use cookies to ensure the functionality and performance of the website. We also like to use analytics cookies to monitor and analyse the use of our website. If you are happy with this, click ‘Accept and Continue’ below or view our cookie policy for more information.</p>
<button id="close_cookie_banner" class="btn btn-custom btn-animate btn-pink"><i class="icon-owia-kokroko"></i> Accept and continue</button>
</div>
</div>
jQuery(document).ready(function($) {
let COOKIE_NAME = "divine_cookie_policy";
if ((getCookie(COOKIE_NAME) === "ACCEPTED")){
// Cookie has been set -> Don't show banner
} else {
// No cookie has been set -> show cookie banner
openCookieBanner();
}
$('#close_cookie_banner').on("click", function (event) {
event.stopPropagation();
closeCookieBanner();
});
/**
* openCookieBanner()
*
* Opens the cookie banner
*/
function openCookieBanner () {
$('#cookie_banner').css({
display: "block"
});
} // END openCookieBanner()
/**
* closeCookieBanner()
*
* Closes the cookie banner
*/
function closeCookieBanner () {
// Prep the date.
var interval = 30;
var date = new Date();
date.setTime(date.getTime() + (interval*24*60*60*1000));
var expires = "expires="+ date.toUTCString();
document.cookie = COOKIE_NAME + "=" + "ACCEPTED" + ";" + expires + ";";
// Close the banner
$('#cookie_banner').css({
display: "none"
});
} // END openCookieBanner()
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 "";
}
}(jQuery));
not really sure what else to try
any help is appreciated

Related

how to save toogle class with cookies? or help me with something similar/alternative to this one

function myFunction() {
{
var element = document.getElementById("body");
element.classList.toggle("bdark");
}
{
var element = document.getElementById("theader");
element.classList.toggle("hdark");
}
{
var element = document.getElementById("sh");
element.classList.toggle("shh");
}
{
var x = document.getElementById("hs");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
}
.bdark {
background-color: #333;
color: white;
}
.hdark {
background-color: black;
color: white;
}
.shh {
display: none;
}
.hs {
display: none;
}
<body id="body" class="light">
<p id="theader">Click the "Try it" button to toggle between adding and removing the class names</p>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is a DIV element.
</div>
<div>
<div id="sh" class="sh">dark black</div>
<div id="hs" class="hs">light white</div>
</div>
i want it's class to be saved so when i refresh or reopen the page it would be same class as it was when i left. or some alternative code that works same. Thanks for Reading This. :)
You can use local storage. Its very simple and better than cookies.
for example to set element bg color (on load):
if(localStorage.getItem("color") == "black") {
element.classList.add("dark"); }
and on your function add :
localStorage.setItem("color",black or white )
Note: You should add an if statement on your function to check if class available set local storage item is set to black or not
add this to end of jquery file (Mrbg => mr babak golbaharan :) )
$.extend({
MrbgSetCookie:function(name,value,days){
var expires = '';
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
},
MrbgGetCookie:function(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;
},
MrbgRemoveCookie:function(name){
document.cookie = name+'=; Max-Age=-99999999;';
},
});
now you can use this for set, get and remove cookies
such as this
$.MrbgSetCookie( 'cookieName', 'cookieValue' , 'period in day' );
in this case:
element = document.getElementById("body");
element.classList.toggle("bdark");
( element.classList.contains('bdark') )?
$.MrbgSetCookie( yourElementID, 'bdark' , 365 ):
$.MrbgRemoveCookie(yourElementID );

set cookie for toggle menu

I'm trying to set a cookie depending on every click on button. I have a button with toggle rule . When user choose open menu-toggle , it should be save cookie for about a week ... The next time (second click ot button - toggle menu is hide) it must change cookie value ...
when cookie value is 1 - menu must be open always, and when value is 2 - menu must be close always ..
button:
<ul class="nav navbar-nav navbar-right">
<li>
<div class="navbar-btn btn-group">
<a href="#" onclick="setMenuSm('1')" id='toggle-button' class="topbar-menu-toggle btn btn-sm" data-toggle="button">
<span class="ad ad-wand"></span>
</a>
</div>
</li>
</ul>
and the java script:
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;
}
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 setMenuSm(){
var cssSelected = $("#toggle-button").hasClass("active");
if (cssSelected !== true) {
setCookie("selectedCSS", "menuopen", 3);
}else{
setCookie("selectedCSS", "menuclose", 3);
}
}
$(document).ready(function() {
getCookie("selectedCSS");
console.log(getCookie("selectedCSS"));
})
... now when click load page console give me "menuopen" and when click on button open gray windows like loading and nothing to do...

get value for a cookie from a bootrap modal with js

I'm trying to create a modal that has 2 options: yes or no. When a user selects no I will create a condition if value=no then do not display modal.
The issue is that I cannot accomplish it. If is answer is yes I can manipulate the info, I need to display a modal asking a question, get the users answer and based on this and do something every 15 days.
my code is currently not working properly
<script>
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
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 "";
}
function checkCookie() {
$('#hewant').on('click', function() {
var valyes = $(this).text();
console.log(valyes);
});
$('#hedont').on('click', function() {
var valno = $(this).text();
console.log(valno);
});
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
$("#myModalcashout").modal();
user = "testing me";
if (user != "" && user != null) {
setCookie("username", user, 15);
}
}
}
</script>
<body onload="checkCookie()">
<div class="modal fade" id="myModalcashout">
<div class="modal-dialog">
<!-- for modal to active manually->
<!-- Modal content-->
<div class="modal-content">
<div class="modal-body">
<p style="text-align:center">test</p>
<p style="text-align:center">question</p>
<p style="text-align:center">for u</p>
<div id="hewant" value="yes"> yes i am </div>
<div id="hedont" value="no"> no i dont</div>
</div>
</div>
</div>
</div>
</body>
I restructured your code for you. For starters you only need 1 listener for both buttons, which can be assigned using class on the buttons in the modal (which I changed from div to button tags.
Note: "Run this code snippet" will not work in this sand boxed environment in regards to cookie manipulation so you will have to test this yourself.
There is now a showModal() function that you will call on load that is responsible for showing your modal and attaching a click listener to both buttons on the modal.
When the user clicks yes or no on the modal we get their answer and pass it to checkCookie() function which does as you ask.
I replaced your create and set cookie functions with ones that are tested and work (also added eraseCookie()) there is a great explanation about all 3 functions Here
showModal();
function showModal() {
// only show modal if cookie for the user is null
var user = readCookie("username");
if (user != null) {
alert("Welcome again " + user);
}
else {
user = "testing me";
$("#myModalcashout").modal();
// add listener on buttons
$('.modalButton').on('click', function() {
$('#myModalcashout').modal().hide();
var answer = $(this).val();
console.log(answer);
// create a cookie with the users answer to the modal
createCookie("username", answer, 15);
});
}
}
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);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://npmcdn.com/tether#1.2.4/dist/js/tether.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<div class="modal fade" id="myModalcashout">
<div class="modal-dialog">
<!-- for modal to active manually->
<!-- Modal content-->
<div class="modal-content">
<div class="modal-body">
<p style="text-align:center">test</p>
<p style="text-align:center">question</p>
<p style="text-align:center">for u</p>
<button class="modalButton" value="yes"> yes i am </button>
<button class="modalButton" value="no"> no i dont</button>
</div>
</div>
</div>
</div>

Input js validation & storing inputed user data in cookies

If name is entered, newsletter class will disappear and newsletter1 class will appear displaying Thankyou for joining, [Nameofuser]
I have a form to input name and email. When the email is entered in correct format, popup appears Successful and I am trying to save that name in cookie. So when I refresh the page, it will display Thankyou for joining, [Nameofuser]
This is what I have achieved so far: I am not able to save the input name in cookies
http://www.w3schools.com/code/tryit.asp?filename=FAEWXAJJ7VKX
https://jsfiddle.net/sachitmaskey/kav5y1ba/
CSS
<head>
<style>
.newsletter {
margin - bottom: 33 px;
}
.newsletter1 {
z - index: 99999;
margin - top: -250 px;
color: red;
}
</style>
</head>
HTML
<body onload = "checkCookie()">
<div class="newsletter" style="float: left;">
<h3>NEWSLETTER</h3>
Name :<input type="text" name="name"><br>
<form name="myForm" onsubmit="return validateForm();" method="post">
Email: <input type="text" name="email">
<br><br><input type="submit" value="Submit">
<p id="demo"></p>
</form>
</div>
<div class="newsletter1" style="float: left;">
<p id="thankyou">
</p><br>
</div>
</body>
</html>
**JAVASCRIPT**
<script>
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var name = document.forms["myForm"]["name"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
alert("Not a valid e-mail address");
return false;
} else {
alert("Successful");
// If name is entered,newsletter class will disapper and newsletter1 class will appear displaying "Thankyou"
if (y > 0) {
$('.newsletter1').css('display', 'block');
$('.newsletter').css('display', 'none');
// setting cookie, getting cookie and checking cookie if it exist or not
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
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);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user = getCookie("name");
if (user != "") {
setCookie("name", user, 30);
document.getElementById("thankyou").innerHTML = "Thankyou for joining...."
}
}
}
}
}
</script>
It's a bit outdated to use cookies and I would use window.localStorage instead.
Much simpler:
localStorage.setItem('name', "John Smith");
console.log(localStorage.getItem('name')); // "John Smith"
localStorage.removeItem('name');
console.log(localStorage.getItem('name')); // null
it is better for you to use cache instead of cookies because there might be some possibilities that the session is made expired by your server which meant every time user visits the page is handled by new session and the old session is destroyed. I recommend you to use browser cache instead.

Reading & using cookie values with javascript

Just off the get go I am incredibly new to javascript, apologies for any silly comments or obvious mistakes in advance.
This is what I'm currently working with:
<div id="currency_select">
<form action="/Default.asp?" method="post" name="CurrencyChoice">
<select onchange="this.form.submit()" name="ER_ID">
<option value="3">EUR</option>
<option value="2">GBP</option>
</select>
<script type="text/javascript">
document.forms['CurrencyChoice'].elements['ER_ID'].value = '';
</script>
</form>
</div>
I want the value from the following cookie "ER%5fID" to be read and then inserted in the value=''field above.
To be completely honest I'm at abit of a loss as I'm not sure what the best way is to read the cookie's value and then have its value inserted where I want.
Once again apologies for any newbie mistakes. I'm having to learn javascript on the fly and I had to start a few days ago.
So I have spent a fair amount of time today trying to figure out what I need which I think is this:
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);
}
}
}
However I'm still unsure as to how to have the appropriate result return within the value field?
Thanks in advance for any assistance.
I am sorry I just do not care to rewrite this, the W3Scools tutorial on cookies is quite comprihensive and even gives you fully completed functions for reading and writing cookies.
It's also a good resource for general JS learning so you should definitely check it out.
The code there is as follows:
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
And usage is:
function checkCookie()
{
var username=getCookie("username");
if (username!="")
{
alert("Welcome again " + username);
}
else
{
username = prompt("Please enter your name:","");
if (username!="" && username!=null)
{
setCookie("username",username,365);
}
}
}
But you can read more in W3Scools own website.
EDIT : So here is the promised fully functional sample in your specific case:
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<title>Cookie Example</title>
<script type="text/javascript">
//adds the [String].trim() method to the [String] object if missing
if(!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g,'');
};
}
var cookieName = "ER_ID";
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++){
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
function setOptionFromCookie() {
var select = document.getElementById('ER_ID'), index, value = getCookie(cookieName);
index = select.options.length;
while(index--) {
if(select.options[index].value == value) {
break;
}
}
if(index > -1) {
select.selectedIndex = index;
} else {
alert('no such value in selection');
}
}
function setValue() {
var value = document.getElementById('value').value;
setCookie(cookieName, value, 365);
}
</script>
</head>
<body>
The value that will go into the cookie "ER_ID": <input id="value" value="2" />
<br/>
<button onclick="setValue()">Set Cookie</button>
<button onclick="setOptionFromCookie()">Set Option from cookie</button>
<hr />
<div id="currency_select">
<form action="/Default.asp?" method="post" name="CurrencyChoice">
<select onchange="this.form.submit()" id="ER_ID" name="ER_ID">
<option value="1" selected="selected">Select Currency</option>
<option value="3">EUR</option>
<option value="2">GBP</option>
</select>
<script type="text/javascript">
</script>
</form>
</div>
</body>
</html>
Because I do not have such a cookie in my browser I also made a possibility for you to set the cookie. But it should be fairly easy to understand. Simply set the cookie first and then press "Set Option from cookie" to read the cookie and set the option based on the value.

Categories

Resources