Why isn't my cookie storing? - javascript

I'm trying to set a cookie on a click event to see if a user has actually clicked the respective button. The button is as follows:
Click here
My js to set the cookie is:
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];
while(c.charAt(0) == '') c = c.substring(1);
if(c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
Then, I set the cookie on a click event:
$("#modalBTN").click(function(){
var clicked = "clicked";
setCookie("clicked", clicked, 30);
console.log(clicked);
});
My click event works. when I console.log(clicked) I see the cookie value, but when I refresh the page the cookie is no longer there.
I check it by:
if(getCookie("clicked") != ""){
//do something else
}
UPDATE
when I call getCookie("otherCookie") it works. But when I call getCookie("clicked") i get returned null. Am I only allowed to have one at a time?

Try this : https://stackoverflow.com/a/24103596/5445351
You can only use console to test the two functions : createCookie & readCookie
Do :
createCookie('ppkcookie','testcookie',7);
Open another page, check if it's still there :
var x = readCookie('ppkcookie')
if (x) {
console.log("ok");
}
Look if it's not your browser that delete cookies automatically.
I tried with Chrome and IE9.

Related

When the user closes the announcement don't show notification to user again

I have created a notification bar on my site that I don't want to be shown to users again on subsequent visits after they close it the first time. The bar works as expected, but I can't seem to get the cookie to work to not display it again
js
$(document).ready(function(){
$(".m-close").click(function(){
$(".m-bar").hide(600);
});
});
html code
<center>
<div class="m-bar m-red">
<a class="m-microphone"><i class="material-icons" style="font-size:26px;">mic</i></a>
<a class="m-content" style="color: white;">Something Text</a>
<a class="m-close" href="#"><i class="material-icons">close</i></a>
</div>
</center> <br><br>
Here is a code example:
function addCookie(name, value, days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
document.cookie = name + "=" + value + expires + "; path=/";
}
function getCookie(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;
}
// When clicking the close button
addCookie('hidden', 'yes', 30);
// Checks if the user chose to hide the announcement
const isHidden = getCookie('hidden');
if (isHidden == 'yes') {
// Hide the announcement
$(".m-bar").hide(600);
}
else {
// Show the announcement
// ...
}
First you can use the addCookie() function to add a cookie when you close the announcement.
After that when you display the announcement, check if the cookie hidden is set to yes, if it is set to yes then hide the announcement, otherwise show it.
Also of course you can use different names and values and expiration dates for your cookies, I recommend setting a long expiration date.
I donĀ“t choose use a Cookie for this, I will use the localStorage because is a simple notification:
$(window).on('load', function(){
//Create a variable for localStorage return
var confirm = {
notification: false
};
//Get the Data from localStorage
let dataconfirm = localStorage.getItem('confirm');
if(dataconfirm != null){
confirm.notification = dataconfirm;
}
console.log(confirm);
$(document).ready(function(){
$('form').on('click', function(e){
e.preventDefault();
if(!confirm.notification === true){
localStorage.setItem('confirm', true);
}
});
});
});

Is there any possibility to execute function only once?

I have this code in JavaScript which is hiding some content. I actually want to hide-the content, before button is clicked. I know that maybe I could have empty elements and fill them after I click that button, but this looks like easier way.
I want to execute this function from the time user enters the page by the time he click on some button - then never, even after refresh.
Is it possible somehow?
function hideTheTable(){
document.getElementsByTagName('table')[0].style.visibility = "hidden"
document.getElementsByTagName('table')[1].style.visibility = "hidden"
document.getElementsByTagName('button')[1].style.visibility = "hidden"
document.getElementById('info').style.visibility = "hidden"
}
hideTheTable();
You can use the localStorage to store whether or not the function has already been run.
function hideTheTable(){
if(!localStorage.getItem('hideTableFlag')){
localStorage.setItem('hideTableFlag', true);
console.log('function run')
}
}
yes you can, by adding a cookie that returns if user entered the page before:
// first lets create a helper function that lets us retreive a 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 "";
}
// setting cookie
// if you need the function to load when the page loads
window.onload = (){
document.cookie = "enteredbefore=true; path=/";
};
// else if you need to call it when user clicks on button (define your button)
mybutton.onclick = (){
document.cookie = "enteredbefore=true; path=/";
};
// now we make if else statment
if(getCookie(enteredbefore) == ""){
// call your function
hideTheTable();
}

How to only show pop up on first page load

I am trying to only display a pop up on the first page load, but in my current script it only shows the pop up if you refresh the page. The popup should display the first time you come to the page but not again.
<script type="text/javascript">// <![CDATA[
document.addEventListener('DOMContentLoaded', function() {
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 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 '';
}
$(document).ready(function() {
if(getCookie('popup') !== ''){
$('.popup-wrapper').css('display','block');
} else {
setCookie('popup','open',1);
}
$('.popup-close').click(function(){
setCookie('popup','close',1);
$('.popup-wrapper').css('display','none');
});
});
});
// ]]></script>
Any help would be greatly appreciated.
Is there a reason why you are using cookies?? If not you can use localStorage and write something a bit cleaner..
So for example
$(document).ready(function() {
// if localStorage doesnt have the shownPopUp item
if(!localStorage.getItem('shownPopUp')){
$('.popup-wrapper').css('display','block');
}
$('.popup-close').click(function(){
// set the shownPopUp item in localStorage
localStorage.setItem('shownPopUp', true)
$('.popup-wrapper').css('display','none');
});
});
});
No need for the getCookie function
Cookies are more used for server-side functions, where localStorage is better for client-side functions. So what will happen here is your users will never see the popup again unless they delete there localStorage
Just add localStorage.setTtem after showing the popup. And don't forget to make the .popup-wrapper display:none
if(!localStorage.getItem('shownPopUp')){
$('.popup-wrapper').css('display','block');
localStorage.setItem('shownPopUp', true);
}

Storing Spaces and Colons in Cookie JavaScript

I am making a webpage with a form that saves the data you type in cookies in case you accidentally close the tab or navigate away before submitting.
I would like to know if there is a way to allow whitespace and colons to be in my cookie's data? For instance if user types "test test", on refresh the cookie will be stored and displayed as "test%2520test". Similarly colons display as "%3A". I believe this is possible with using encodeURIComponent but I am not sure exactly how. Below I will include my saveVideo, setCookie, and readCookie JS functions as well as an example input field.
Also, bonus question: What would be the best way to delete each cookie's data upon submit of the form?
<input id="video" name="video" type="text" onchange="saveVideo(this.value);"/>
function saveVideo(cookieValue)
{
var sel = document.getElementById('video');
saveclass = saveclass ? saveclass : document.body.className;
document.body.className = saveclass + ' ' + sel.value;
setCookie('video', cookieValue, 1 );
}
function setCookie(cookieName, cookieValue, nDays) {
var today = new Date();
var expire = new Date();
if (nDays==null || nDays==0)
nDays=1;
expire.setTime(today.getTime() + 60 * 60 * 1000);
document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();
}
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;
}
</script>
Any tips, pointers, general help is much appreciated!
Just change your code to following in the readCookie function, using decodeURIComponent:
return decodeURIComponent(c.substring(nameEQ.length, c.length));

Cookies in HTML page

So this code that i have works perfectly and exactly as i want it to. What is does is it takes the input "textmoney" and calculates how much money you make yearly. I have a link to another calculator that makes a more percise prediction. Basically i want to know how to have the website remember what the data input was on "textmoney" on the first page, so that when the user clicks on the more advanced calculator the website will remember the value of "textmoney" and the user won't have to type in the same data again. Do i use cookies?
Code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
var $demo = $('#demo');
var $textMoney = $('#textmoney');
var $moneydiv = $('#moneydiv');
$('#advanced').hide();
function getmoney(){
var money = $textMoney.val();
if (isNaN(money) || money === '') {
$demo.text('You aint enter no $$$$$$');
} else {
var dailyE = $textMoney.val() * 365;
$demo.text('$' + dailyE + ' per day');
}
}
// on enter key
$textMoney.keydown(function(e) {
if (e.which === 13) {
getmoney();
$('#advanced').show();
} else if ($(this).val() === '') {
$demo.text('');
$('#advanced').hide();
}
}).mouseover(function() {
$(this).css('border', '1px solid black');
}).mouseout(function() {
$(this).css('border', '1px solid grey');
});
// on click
$moneydiv.click(function(){
getmoney();
$('#advanced').show();
});
});
</script>
You may use HTML5 Web Storate:
// Store
localStorage.setItem("textmoney", $textMoney.val());
// Retrieve
$textMoney.val(localStorage.getItem("textmoney"));
From W3Schools:
The data in localStorage will not be deleted when the browser is closed, and will be available the next day, week, or year.
If you want to store the value just while the browser (or tab) is open. You can use sessionStorage instead:
// Store
sessionStorage.setItem("textmoney", $textMoney.val());
// Retrieve
$textMoney.val(sessionStorage.getItem("textmoney"));
If your browser desn't support HTML5, cookies are also good idea but be aware that some browsers can also have blocked cookies.
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
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];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
// Store
setCookie("textmoney", $textMoney.val(), 999999 /* Expiration*/);
// Retrieve
$textMoney.val(getCookie("textmoney"));

Categories