Reputation: 7688
How can I set a cookie via jQuery cookie ($.cookie()
) library, only when the page is loaded for the first time? I currently have a toggle feature, to change the value of the cookie in question upon a click
event
$('.family-filter').click(function() {
if ($.cookie('ff') == null) {
$.cookie('ff', 'on', {
expires: 1,
path: '/'
});
} else {
$.cookie('ff', null, {
path: '/'
});
}
});
But I need a default value, if none is set already.
Also happy to set it via PHP, but I'd prefer for this case, to do it via Javascript
Upvotes: 1
Views: 10263
Reputation: 36
In page load you can set this code to check and set cookies
<?php
if (!isset($_COOKIE["ff"])) {
// Expire Time is 30 Days
$expire = time() + 60 * 60 * 24 * 30;
setcookie('ff', 'on', $expire);
}
Upvotes: 2
Reputation: 7688
Well, I decided to implement it this way:
if ($.cookie('ff') == null) {
$.cookie('ff', 'on', {
expires: 30,
path: '/'
});
}
$('.family-filter').click(function() {
if ($.cookie('ff') == 'off') {
$.cookie('ff', 'on', {
expires: 30,
path: '/'
});
} else {
$.cookie('ff', 'off', {
path: '/'
});
}
});
Upvotes: 1
Reputation: 9731
I'm adding a cokkie like so:
if (document.cookie.indexOf('visited=true') == -1) {
var thirtydays = 1000*60*60*24*30;
var expires = new Date((new Date()).valueOf() + thirtydays);
document.cookie = "visited=true;expires=" + expires.toUTCString();
}
It works fine for me, and you can add some more code inside the if
clause if you need something to run while the user it's on his first visit on the website.
Upvotes: 2