javascript define cookie - javascript

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

Related

Run a function if a cookie exists

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.

IE doing logout after close the browser

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.

The cookie is deleted when the browser is closed

I have this cookie to store users previous selection from a menu. But I want keep this cookie stored in the browser even if the user closes the browser. This code perfectly works on IE but when I close Chrome and Firefox, the cookie getting deleted. Can anyone provide me solution for this.
function setCookie(NameOfCookie, value, expiredays) {
var ExpireDate = new Date();
document.cookie = NameOfCookie + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString());
}
function delCookie (NameOfCookie) {
if (getCookie(NameOfCookie)) {
document.cookie = NameOfCookie + "=" + "; expires=Thu, 17-Jul-24 00:00:01 GMT";
}
}
If you call the function with
setCookie('redirectcountry', 'CA')
then you set the expiry date to new Date(), that is "right now". So it's normal behavior to have the cookie be immediately deleted.
Simple solution : call it as
setCookie('redirectcountry', 'CA', true)
Did you check your browsers settings? In Firefox this is option called 'Keep until' with value 'I close Firefox' (Privacy tab).

How to create a global cookie in javascript?

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

Html page on reload different html

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

Categories

Resources