I've created a Django website, and need a cookie to be stored and readable from any part of the site. The javascript for it is in every part I need it in, but for some reason the cookie itself is stored seperately for each page. E.g. if the cookie is equal to "set" on one page, it can be undefined on another. Here's the code I'm using to create, get, and read the cookie (the "createBannerCookie()" method is called when a specific button, found on every page, is pressed)-
<script type="text/javascript">
$(document).ready(function() {
$('#banner').hide();
checkBannerCookie();
});
function createBannerCookie()
{
$('#banner').hide();
var exdate=new Date();
exdate.setDate(exdate.getDate() + 3);
var c_value=escape("set") + ((exdate==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie='banner=' + 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 checkBannerCookie()
{
var banner=getCookie("banner");
if (banner!=null && banner!="")
{
$('#banner').hide();
}
else
{
$('#banner').show();
}
}
</script>
Any suggestions?
By default, cookies are accessible only to web pages in the same directory as the web page which originally created the cookie. Please try to add "path=/" option. e.g.
document.cookie =
'propertyName=test; path=/'
SImon,
I think your problem is the expiration date on your cookies. It looks to me like you are setting them to expire 3 miliseconds after being created.
Try something like this in your "createBannerCookie" function (instead of the w3schools version):
function createBannerCookie()
{
$('#banner').hide();
var exdate=new Date();
exdate.setTime(exdate.getTime()+(3*24*60*60*1000)); // the 3 in that math is your days
var c_value=escape("set") + ((exdate==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie='banner=' + c_value;
}
Reference: http://www.quirksmode.org/js/cookies.html
Related
Okay, I'm new to javascript coding, cookies etc., and I can't quite find the answer to my problem on the net. I'm trying to create a site that has a div that displays some helpful information at the top.
<div id="helpdiv">
<!--This content shows only on web browsers Internet Explorer 6/7/8/9/10/11 and Microsoft Edge.-->
Looks like your using Internet Explorer/Edge. This site is optimized when "Compatibility Mode" is disabled. Thank you!
</div>
I found some code that I can use that will show this div for 8 seconds, then disappear. But I want this to only show up once.
function closeHelpDiv(){
document.getElementById("helpdiv").style.display=" none";
}
// close the div in 8 secs
window.setTimeout( closeHelpDiv, 8000 );
I figured if a cookie was used, then the browser could check for that cookie, and if it existed, then it wouldn't need to show the div. Only the first time they visited the site.
So here's the flow I'm trying to acheive:
Check for a cookie named “helpText”
If the cookie doesn’t exist:
I want to run a function that hides a div (id="helpdiv") after 8 seconds of showing.
Here is some code I found that hides a div:
function closeHelpDiv(){
document.getElementById("helpdiv").style.display=" none";
}
// close the div in 8 secs
window.setTimeout( closeHelpDiv, 8000 );
I then want to set a site cookie called ”helpText” so that next time they visit the site, the function won’t run again.
If cookie exists:
I want the div with an Id of “helpdiv” to have the style=“display:none;”
If I need to add anymore code, please let me know and I can explain more. Any help would be a life saver!!
You can check for cookies on the current web document like this:
document.cookie
So if you are planning to check for a specific string you could do an indexOf("") with the word you are looking for and validating if the index is more than 0.
if(document.cookie.indexOf("helpText") > 0 ){
the cookie was found, so your function should be here
}else{
cookie not found
}
Probably is better to do a search over Stackoverflow because there are a lot of answers about cookies and javascript:
Here It's a full answer about this:
Check if cookie exists else set cookie to Expire in 10 days
Extending on Lemmy's answer, this is what you need:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var myCookie = getCookie("helpText");
if (typeof myCookie === 'undefined') {
// close the div in 8 secs
window.setTimeout( closeHelpDiv, 8000 );
}
function closeHelpDiv(){
document.getElementById("helpdiv").style.display=" none";
}
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
});
</script>
Here is the updated script for your wordpress environment:
<script type="text/javascript">
jQuery(document).ready(function($){
var myCookie = getCookie("helpText");
if (typeof myCookie === 'undefined') {
// close the div in 8 secs
window.setTimeout( closeHelpDiv, 8000 );
//setTimeout(closeHelpDiv, 2000);
}
function closeHelpDiv(){
document.getElementById("helpdiv").style.display=" none";
}
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
});
</script>
In Wordpress you must use change the $ sign with jQuery and pass the $ sign into the function. The dollar sign in $(document).ready(function(){}); is not used for compatibility with other libraries.
try
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
from
Get cookie by name
Use it to check whether the cookie exists or not.
In your code you can easily
if(getCookie('helpText')!=''){
$('selector').css('attrib','prop');
}
So you need to set a cookie after displaying banner to user on her first visit -
function closeHelpDiv(){
document.getElementById("helpdiv").style.display=" none";
document.cookie="visitedBefore=true; expires=1 Jan 9999 12:00:00 UTC; path=/";
}
check with following code if that user already visited your site
function showBanner(){
// check if visited Earlier
if(!getCookie('visitedBefore'))){
window.setTimeout( closeHelpDiv, 8000 );
}
}
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
showBanner();
So you are doing all things correct just use cookies as described above.
I craete web-sites and when user login and check "remember me" I write to cookies username. It is working good, but just in some browsers.
My code for write in cookies username:
document.cookie = "";
document.cookie = "username=" + username;
And after login i check username from cookies.
But in IE browser it is not working.
After close the browser and open him again cookies doing clears.
Why it is happend?
And how to fix it?
I found good code for get/set cookies:
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);
}
}
}
Source:How do I create and read a value from cookie?
Thanks you heru-luin
Check this checkbox in browser settings: http://browsers.about.com/od/internetexplorertutorials/ss/ie8privatedata_8.htm
See the official MS Developer Network docs -> https://msdn.microsoft.com/en-us/library/ms533693%28v=vs.85%29.aspx
If you set no expiration date on a cookie, it expires when the browser
closes. If you set an expiration date, the cookie is saved across
browser sessions. If you set an expiration date in the past, the
cookie is deleted. Use Greenwich Mean Time (GMT) format to specify the
date.
So you basically need to specify an expiration date if you want the cookie to persist in IE. Example from the link above :
// Create a cookie with the specified name and value.
function SetCookie(sName, sValue)
{
document.cookie = sName + "=" + escape(sValue);
// Expires the cookie in one month
var date = new Date();
date.setMonth(date.getMonth()+1);
document.cookie += ("; expires=" + date.toUTCString());
}
Or see this excellent answer -> Using javascript to set cookie in IE.
I have the follwing code :
<script type="text/javascript">
function myfuncc () {
if (document.cookie.indexOf("visited") >= 0) {
// They've been here before.
alert("hello again");
}
else {
// set a new cookie
expiry = new Date();
expiry.setTime(date.getTime()+(10*60*1000)); // Ten minutes
// Date()'s toGMTSting() method will format the date correctly for a cookie
document.cookie = "visited=yes; expires=" + expiry.toGMTString();
alert("this is your first time");
}
}
</script>
<script type="text/javascript">
window.onload = myfuncc;
</script>
As you can see the window.onload function, I am trying to check if a vistor had already been at the site once the page loads. I am using cookies to do so. Problem is, I can't see the messages I am supposed to. Anyone knows why?
You have to set the expire date using toUTCString() method.
You also have a date object that is not initialized, try this:
function myfuncc () {
if (document.cookie.indexOf("visited") >= 0) {
// They've been here before.
alert("hello again");
}
else {
var expiry = new Date();
expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes
document.cookie = "visited=yes; expires=" + expiry.toUTCString();
alert("this is your first time");
}
}
give this a try:
var testarr = ["knirpsel", "text", "visited=yes"].indexOf("visited");
alert ( testarr );
output is "-1" which means the string "visited=yes" won't be found by search term "visited"
http://jsfiddle.net/m5x3M/
and
What is the best way to get a cookie by name in JavaScript?
First time html loads and it display text as Yes and second time when reloads or loads from cache it should display some other text NO.
As you're using jQuery, it seemed easiest to use the jQuery Cookie plugin:
// assigns the value returned by the cookie to the variable,
// if no cookie, or no value, is returned, the string is assigned instead.
var cookieValue = $.cookie('firstVisit') || 'Yes';
// if there's no cookie, then a cookie is set.
if (!$.cookie('firstVisit')) {
$.cookie('firstVisit', 'No', {
expires: 7 // expires in 7 days, adjust to taste.
});
}
$('#firstVisit').text(cookieValue);
JS Fiddle demo.
The above code updated to be a little tidier, and less repetitive:
// if the cookie is not set, the cookieVal variable is falsey
var cookieVal = $.cookie('firstVisit'),
// creating a reference to the relevant div
div = $('#firstVisit');
// if the cookieVal evaluates to false the cookie is set,
// and the text of the div is 'Yes'
if (!cookieVal) {
$.cookie('firstVisit', 'No');
div.text('Yes');
}
// otherwise...
else {
// text of the div is equal to the value returned from the cookie
div.text(cookieVal);
}
JS Fiddle demo.
You can use cookies to recognize a returning visitor:
<html>
<body>
<script language="javascript">
// sets a cookie with a certain name, value and optional expiration in days
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;
}
// retrieves the value of a cookie of a certain name (or returns undefined)
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);
}
}
// if the cookie was set, then the user has been here already
if (getCookie("visited") == "true") {
document.write("NO");
} else {
// otherwise, set the cookie and assume the user has not been here before
setCookie("visited", "true");
document.write("YES");
}
</script>
</body>
</html>
See: http://en.wikipedia.org/wiki/HTTP_cookie
Something very wrong is going on this piece of code:
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 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 checkCookie()
{
var username=getCookie("username");
if (username=="username"){
document.getElementById(mydivx).style.display = 'block'; }else{
document.getElementById(mydivx).style.display = 'none';
}
}
and a button to define the cookie:
esconder
So this should be happening, if the button is clicked, it defines a cookie named "username" with the value "username", the getcookie function gets the cookie username and its value.
What am i doing wrong?
Hope you can help me guys !
EDIT: SOLUTION:
Just remove the ";" from the call, and add some single quotations to the code from the button:
esconder
Thanks to stealthyninja
In your HTML code, replace
esconder
with
esconder
The return false is so that your browser doesn't actually browse to the href which would make a hash (#) appear in your address bar. In other words, it's similar to preventing the default action of clicking on the link without JavaScript to prevent it.
Update
The second username should be a variable or string. username by itself is undefined.
your setcookie never got called I beleive try this:
esconder
esconder
You have an error in that code. onClick="" and "username"... Try:
esconder
Not sure if this is all of it, but this line:
esconder
Has a problem, since you're terminating the string. You're using double quotes inside double quotes; try
esconder