tags:

views:

99

answers:

1

Hi guys, i'm using the jquery cookie plugin. Everything works fine except the fact that I have no idea how to set an expiration-time for the cookie?

$.cookie('opt_visible', 'true');

the jquery-cookie documentation says:

hoursToLive (DEPRECATED for expiresAt)

  • NUMBER
  • For how many hours should the cookie be valid? (Passing 0 means to delete the cookie at the end of the browser session--this is default. Negative values will delete the cookie, but you should use the del() method instead.)

That's exactly what I'd like to have. The cookie should be available as long as i'm browsing the site. As soon as i close the window or browsertab, the cookie should be deleted.

How can i implement this hoursToLive thingy to my mentioned line above?

Thank you

A: 

To my understanding you don't need to do anything at all. hoursToLive is deprecated but not removed yet. As 0 is the default for hoursToLive anyway the cookie will be removed when the browser is closed (!not when only the tab is closed but the browser remains open).

If you really need to remove the cookie when the tab is closed you could try attaching an event handler to the window unload event jQuery(window).unload(...) and inside that handler call the del('...') but that might not always work


If it's enough that the cookie expires after e.g. 1 hour you can simply pass in the expiresAt option when setting the cookie

expiresAt: new Date(new Date().getTime()+3600000) //now + 1h (60*60*1000)
jitter
The problem is: I want to load a certain overlay-div that lies on top of my website. It should only appear when the site is loaded the first time. This div is closable (it actually just hides if i click the closebutton). If I don't set a cookie and click for instance some internal link on my website the overlay-div gets shown again. So i want to set a cookie that lives until i close the window or tab. It would be also okay if the cookie lives for an hour or so. But i have no idea how to implement that!
Check expanded answer for 1h solution
jitter