Pregunta

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

¿Fue útil?

Solución 3

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

Otros consejos

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.

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);
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top