Rasel Ahmed
Rasel Ahmed

Reputation: 305

jQuery cookie is not expring

I am using this jQuery cookie plugin for create & display cookie.

var date = new Date();
var minutes = 2;
date.setTime(date.getTime() + (minutes * 60 * 1000));        

$.cookie('the_cookie', 'the_value', { expires: date });

alert($.cookie('the_cookie'));

I set two minutes (for test, usually I will use one hour. Explained below.), but if I visit the page again after two minutes, it is still displaying cookie alert.

What I want to do

I want to display a message to my website for one hour timing. It means, when visitor open my website first time, visitor can see the message. When visitor clicks on other page, the message will not show. After one hour, the message will show again.

How can I set minutes, hours as well as days?

Here is my codes fiddle.

Upvotes: 0

Views: 63

Answers (3)

sideroxylon
sideroxylon

Reputation: 4416

If you're not worried about IE8 and earlier, you can just use max-age and straight javascript as a simpler solution:

if (document.cookie.indexOf('the_cookie') == -1) {
//show message
document.cookie = 'the_cookie;path=/;max-age=120;';
}

This shows the message and sets a 2 minute cookie if the cookie has not been set previously or has expired.

Upvotes: 0

bvaughn
bvaughn

Reputation: 13497

That's because you're showing the alert after you create/recreate the cookie. :)

If you move alert($.cookie('the_cookie')); to the start of your code snippet, your cookie will disappear in 2 minutes.

Just use Chrome's Resources > Cookies tab to verify. :)

Here's an updated test harness that will also show the cookie expiring: http://jsfiddle.net/bvaughn/860rr2Ly/

if ($.cookie('temporaryCookie')) {
    alert('Cookie still set');
} else if ($.cookie('longerCookie')) {
    alert('Cookie expired at ' + $.cookie('longerCookie'));
} else {
    alert('Cookie never set');
}

var expiresAt = new Date();
expiresAt.setTime(expiresAt.getTime() + 5000); // 5 secs

$.cookie('longerCookie', new Date());
$.cookie('temporaryCookie', true, { expires: expiresAt });

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388436

You can try

var thecookie = $.cookie('shown');
if (!thecookie) {
    var date = new Date();
    var delay = 20 * 1000;
    date.setTime(date.getTime() + delay);

    $.cookie('shown', 'true', {
        expires: date
    });
    $('body').html('show the message')
}

Demo: Fiddle

Upvotes: 0

Related Questions