简体   繁体   中英

Set a cookie on first time page load

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

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);
}

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.

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: '/'
        });
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM