Reputation:
i have cookie code which is not working dont know whats the problem.This code is working in another script but not in it.
CODE:
function get_cookie(Name) {
var search = Name + "=";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
// cookie exist, update expiry date of the same cookie
if (offset != -1) {
cookie_info = document.cookie.split('=');
cookie_info = cookie_info[0]+"=" + cookie_info[1];
// add 30 days expiry
var date = new Date();
date.setTime(date.getTime()+(30*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
cookie_info += expires + ";path=/";
document.cookie = cookie_info;
}
}}
function loadCokie() {
if (get_cookie('popup')=='') {
alert("hello");
document.cookie="popup=yes"
}
}
THnx in advance
Upvotes: 0
Views: 266
Reputation: 318342
Just a suggestion, but you could just do:
if ( ! localStorage.getItem('visited')) {
localStorage.setItem('visited', true);
alert('Hello, new visitor !');
}
and if you have to support older browsers, you'd add the polyfill from MDN that falls back to cookies automagically.
EDIT:
As for your original code, you never execute any of the functions, and if a cookie doesn't exist, it wont return an empty string, so the logic is flawed, I changed it a little :
function get_cookie(c_name) {
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1) {
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1) {
c_value = null;
}else{
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1) {
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}
function set_cookie(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 loadCokie() {
if ( ! get_cookie('popup')) {
alert("hello");
set_cookie('popup', 'yes', 30);
}
}
loadCokie();
Upvotes: 1