admin管理员组文章数量:1404073
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
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
Share Improve this question edited Feb 3, 2016 at 8:59 Alex asked Jan 30, 2012 at 18:19 AlexAlex 7,68825 gold badges86 silver badges153 bronze badges 3- You want to set the cookie on CLICK or on LOAD? You're clearly setting the cookie on click. $.ready for on page load. – MatBee Commented Jan 30, 2012 at 18:25
-
I don't think you need the
else if
. Checking if it is null and then creating it should be enough – My Head Hurts Commented Jan 30, 2012 at 18:29 -
yea, the
else if
not needed... I forgot to take it out. Theelse
is needed to set it off by link if is on and vice versa. @MatBee, I've tried setting it on$.ready
but I ended overwriting the code above – Alex Commented Jan 30, 2012 at 18:46
3 Answers
Reset to default 2I'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.
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);
}
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: '/'
});
}
});
本文标签: javascriptSet a cookie on first time page loadStack Overflow
版权声明:本文标题:javascript - Set a cookie on first time page load - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744214927a2595591.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论