I have written this code. But it isn't displaying cookie. It displays only prompt again and again, whenever I open this page. How can I correct it?
<body onload="myFunc()">
<script>
function createCookie(value, exdays)
{
var date= new Date();
var d= date.setTime(date.getDate()+(exdays*10000));
var e = date.toUTCString(d);
var g = document.cookie= "user="+value+";"+" "+"expires="+e;
return g;
}
function readCookie()
{
var h = document.cookie;
var i= h.split(";");
return i[0];
}
function myFunc()
{
var a= readCookie();
if(a!="")
{
alert("Welcome"+a);
}
else
{
var b = prompt("Enter your name", "");
createCookie(b, 5);
}
}
Javascript IS case sensitive:
var date = new Date();
Your snipped works fine in most browsers, even in chrome. Except you are working on your local file-system (URL = file:///xxx). Chrome has local file cookies on default disabled but you can activate them with command-parameters '--allow-file-cookies'.
Related
I am developing a JavaScript for a webpage. This script has to create a popup, when the user is idle for a certain time. When the popup shows up, the user can choose to either close the popup or to minimize it.
In case of closing the popup, further opened pages within the website shall not open the popup anymore. In case of minimizing, it should not do either. Nonetheless when the user has a certain idle time on any page the first time, it shall appear.
It works in so far, that the pop up is created and also the closing of the pop works (and that it does not open anymore). But it does not work a refresh of the page anymore. So the storing does not work. And I know it is, because of my variables and a refresh also restarts the script again, so the initialization of the variables does rewrite the session value.
So basically my question is: How do it do the 1st time initialization of the variables, which than are furtherly used after a refresh?
My code is the following:
var isClosed = new Boolean(false);
var isShrinked = new Boolean(false);
var test = "Tesst";
sessionStorage.setItem("session", isClosed=false);
function close_popup() {
$('#' + 'box').fadeOut('slow');
sessionStorage.setItem("session", isClosed=true);
}
(function idelor(){
document.onclick = document.onmousemove = document.onkeypress = function() {
idleCounter = 0;
};
window.setInterval(function() {
if (sessionStorage.getItem("session").toString() == "false") {
if (isShrinked == false) {
if (++idleCounter >= IDLE_TIMEOUT) {
var scriptCode = document.createElement('p');
scriptCode.id = 'Sentotal';
document.getElementsByTagName('body')[0]
.appendChild(scriptCode);
document.getElementById("Sentotal").innerHTML = boxTotal;
}
}
}
}, interval);}());
You can use cookie for this matter.
//A simple function to get the value stored in cookie;
var getCookie = name =>
document.cookie.split(';')
.map(token => token.trim('').split('='))
.reduce((prev, curr) =>
(prev[curr[0]] = curr[1]) && prev, {})[name],
myPopup = () => {
if (!getCookie('noPopUp')) {
console.log('your popup logic');
document.cookie = 'noPopUp=true'
}
},
reset = () => {
document.cookie = 'noPopUp=true; expires=' + new Date();
};
reset(); //Remove this and myPopUp will do nothing until you restart your browser.
myPopUp();
myPopUp();
Cookie resets (by default) when browser closes.
I used Hin Fan Chan's suggestion of using cookies, and have the following, stable working solution coded:
Just two variables now as constant names for the Cookies:
var CLOSE_CONSTANT = "CloseCookie";
var MINIMIZE_CONSTANT = "MinimizeCookie";
Simple functions for creating and getting the cookies. Note, that "error" in getCookie(...) is very important for the initialization of the script!:
function setCookie(name, state) {
var cname = name;
var value = state;
document.cookie = cname + "=" + value;
}
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 "error";
}
I also build a cookieChecker(...) function, which automatically fills error-Cookies (those, who are not existing atmo) with "false":
function cookieChecker(name) {
switch (getCookie(name)) {
case "error":
setCookie(name, "false");
break;
default:
break;
}
}
Now the final function, which is the only function being opened by the HTML. cookieChecker(...) is used twice: For the minimization and the closing of the popup. These two functions simply set the state of a cookie to true (and fading the box out):
(function idelor() {
var minutes = false;
var interval = minutes ? 60000 : 1000;
var IDLE_TIMEOUT = 5;
var idleCounter = 0;
document.onclick = document.onmousemove = document.onkeypress = function() {
idleCounter = 0;
};
cookieChecker(MINIMIZE_CONSTANT);
cookieChecker(CLOSE_CONSTANT);
window
.setInterval(
function() {
switch (getCookie(CLOSE_CONSTANT) + " "
+ getCookie(MINIMIZE_CONSTANT)) {
case "false false":
if (++idleCounter >= IDLE_TIMEOUT) {
var scriptCode = document.createElement('p');
scriptCode.id = 'Sentotal';
document.getElementsByTagName('body')[0]
.appendChild(scriptCode);
document.getElementById("Sentotal").innerHTML = BOXTOTAL;
}
default: break;
}
}, interval);
}())
I am working on a script which takes the vertical scroll posistioning of a div container and on document unload it stores the vertical posistion within a cookie and then loads it on load.
Originally I had the following:
$('#GridViewContainer').load('claims.php', function() {
$(this).scrollTop($(this).prop("scrollHeight") - $(this).height());
});
Which is ok if you are refreshing the page but if you are reloading the page with parameters it will lose it's position. Solution? Store it in a cookie...
However I am having issues with storing the value and loading it on load. I am using php to return all current Cookies and I can see I am setting the cookie "div_yCookie" but the content seems to be:
'div_yCookie' => string '[object Object]' (length=15)
(I am a complete Javascript and jQuery novice... No doubt it is something obvious but can someone help?
<script>
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);
}
$(document).ready(function () {
$('#GridViewContainer').load('claims.php', function() {
var x = readCookie('div_yCookie');
$(this).scrollTop($(this).prop("scrollHeight") - x);
//$(this).scrollTop($(this).prop("scrollHeight") - $(this).height());
});
});
window.onbeforeunload = function(){
var div_y = $('#GridViewContainer').scrollTop($('#GridViewContainer').prop("scrollHeight") - $('#GridViewContainer').height());
createCookie('div_yCookie',div_y,0.5);
};
</script>
UPDATE
It turns out it actually works when you refresh the page however it still doesn't work when you reload the page.
var openClose = $('.openClose');
openClose.on('click', function() {
var cook = ReadCookie('slideHide'),
miniParent = $(this).parent().parent().parent().children('.main-content'),
miniDisp = miniParent.css('display');
if (miniDisp ==="block") {
KillCookie('slideHide');
$(this).parent().parent().parent().children('.main-content').slideUp();
var slide = cook + "," + "#"+$(this)
.parent()
.parent()
.parent()
.parent().attr("id") +
" #"+$(this).parent()
.parent().parent().attr("id");
SetCookie('slideHide', slide, 100);
}
else
{
$(this).parent().parent().parent().children('.main-content').slideDown();
var newCookie=[];
var a= $('.module').children('.main-content').filter(":hidden");
for(var i=0;i<a.length;i++){
var d = $(a[i++]);
var c = "#"+d.parent('.module').attr('id');
}
newCookie= c;
console.log(newCookie);
KillCookie('slideHide');
SetCookie('slideHide',d, 100);
}
});
These are my cookie functions:
function SetCookie(cookieName,cookieValue,nDays) {
var today = new Date();
var expire = new Date();
if (nDays==null || nDays==0) nDays=1;
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue)
+ ";expires="+expire.toGMTString(),';path = /';
}
function KillCookie(cookieName) {
SetCookie(cookieName,"", - 1);
}
function ReadCookie(cookieName) {
var theCookie=""+document.cookie;
var ind=theCookie.indexOf(cookieName+"=");
if (ind==-1 || cookieName=="") return "";
var ind1=theCookie.indexOf(";",ind);
if (ind1==-1) ind1=theCookie.length;
return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}
Setting the cookie to make it slideUp and stay hidden works, but when I try to open it, it slidesDown, then I refresh the page it doesn't stay open like it should.
To sort of get the picture - http://jsfiddle.net/zRT9u/
If you need to know more please ask me I am willing to provide more!
I edited the javascript it almost works but I am not getting all the objects that I need
NEW EDIT- Tried the $.map() function but when I open one, and refresh all of them are now open?
else {
$(this).parent().parent().parent().children('.main-content').slideDown();
KillCookie('slideHide');
var newCookie=[];
var a= $('.module').children('.main-content').filter(":hidden");
var c = $.map(a,function(n,i){
return $(n).parent().attr('id');
});
newCookie= c;
SetCookie('slideHide',newCookie, 100);
}
Fixed it by using $.map and .join()
var openClose = $('.openClose');
openClose.on('click', function() {
var cook = ReadCookie('slideHide'),
miniParent = $(this).parent().parent().parent().children('.main-content'),
miniDisp = miniParent.css('display');
if (miniDisp ==="block") {
KillCookie('slideHide');
$(this).parent().parent().parent().children('.main-content').slideUp();
var slide = cook+","+ "#"+$(this).parent().parent().parent().attr("id");
SetCookie('slideHide', slide, 100);
} else {
$(this).parent().parent().parent().children('.main-content').slideDown();
KillCookie('slideHide');
var newCookie=[],
a= $('.module').children('.main-content').filter(":hidden"),
c = $.map(a,function(n,i){
return "#"+$(n).parent().attr('id');
});
newCookie= c.join(',');
SetCookie('slideHide',newCookie, 100);
}
});
By creating a "global" array and then using the $.map function as well as adding "#"+ to the map function I was able to get the actual ID names. Then I set newCookie to c.join(',') and everything works perfectly after that!
I am trying to hide random multiple elements, so what I have done was given each a unique ID.
$(function() {
var left= $('#left'),
right = $('#right'),
heads = $('.maintitle'),
i,
leftHead = $(left).find(heads),
rightHead = $(right).find(heads);
$(leftHead).prepend('<div class="close"></div>');
$(rightHead).prepend('<div class="close"></div>');
var close = $('.close'),
Lnumber = $('#left .module'),
Rnumber =$('#right .module');
for (i=0;i<Lnumber.length;i++) {
$(Lnumber)[i].id='widg'+i;
}
close.click(function() {
var id = $(this).parent().parent().attr('id');
$(this).parent().parent().slideUp().addClass('hidden');
SetCookie('hidden'+id,"true",100);
});
var cookieId = $('#left .module');
for (i=0;i<cookieId.length;i++) {
var newArray = [cookieId[i].id];
if (ReadCookie(newArray) == 'true') {
var cName = newArray.replace('hidden','');
alert(cName);
}
}
});
As you can see in the ReadCookie function I have it alerting the ID's that are hidden, though this doesn't work either yet. I am brand new to Cookies and just having a hard time getting this to work correctly.
Here are the functions for the cookies...
function SetCookie(cookieName,cookieValue,nDays) {
var today = new Date();
var expire = new Date();
if (nDays==null || nDays==0) nDays=1;
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue)
+ ";expires="+expire.toGMTString(),';path = /';
}
function KillCookie(cookieName) {
SetCookie(cookieName,"", - 1);
}
function ReadCookie(cookieName) {
var theCookie=""+document.cookie;
var ind=theCookie.indexOf(cookieName+"=");
if (ind==-1 || cookieName=="") return "";
var ind1=theCookie.indexOf(";",ind);
if (ind1==-1) ind1=theCookie.length;
return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}
If anyone sees any other way to do this that is fine, just need to get the specific ID's to make sure they stay hidden when clicked and changing pages.
Have you tried the jQuery Cookie plugin?
https://github.com/carhartl/jquery-cookie
Then create expiring cookie, valid across entire site:
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });
Then to read the cookie:
$.cookie('the_cookie'); // => "the_value"
I have been trying this piece of code on a page and it is working fine in Chrome as well as Firefox.
But not in Internet Explorer, only the alert function within the if condition will show up.
$('#element-14').change(
function(){
$('.late').hide();
$('.normal').hide();
var tempDate= new Date();
var dateViolatetmp = $('#element-14').val();
var dateViolatearr = dateViolatetmp.split('/');
var dateViolate= new Date(dateViolatearr[2],(parseInt(dateViolatearr[0],10)-1).toString(),dateViolatearr[1]);
var one_day=1000*60*60*24;
var tempDate_unixtime =tempDate.getTime() ;
var dateViolate_unixtime =dateViolate.getTime();
var dayDifference = Math.round((tempDate_unixtime/one_day)) - Math.round((dateViolate_unixtime/one_day));
if(dayDifference<=30){
$('.normal').show();
alert("ok1");
}
else{
$('.late').show();
alert("ok2");
}
});
Do you see all the values as expected in the console with this code? The reason I wrote if(console) conditions is because I'm not sure if it even exists in IE (otherwise would not surprise me a bit(!) and I don't have it installed).
$('#element-14').change(function() {
if (console) console.log('#element-14 changed.');
$('.late, .normal').hide();
var arr = $('#element-14').val().split('/');
if (console) {
console.log('val:',$('#element-14').val());
console.log('arr:',arr);
}
var dateV = new Date(parseInt(arr[2]), parseInt(arr[0])-1, arr[1]);
if (console) console.log('dateV:',dateV);
var one_day = 1000*60*60*24;
var now = new Date();
if (console) console.log('now:',now);
var dayDiff = Math.round((now.getTime()-dateV.getTime()) / one_day);
if (console) console.log('dayDiff:',dayDiff);
$(dayDiff <= 30 ? '.normal' : '.late').show();
});