Search code examples
javascriptjquerycookiesjquery-cookie

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


Solution

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