1
onClick="javascript:document.cookie='n=1'"

Im new in javascript

I have a btn click will set cookie, how can I set expire time 1 hour on this cookie?

Ben
  • 2,562
  • 8
  • 37
  • 62

3 Answers3

3

When you write the cookie to the browser, you need to specify an expiration date or a max age. However, note that max-age is ignored by Interent Explorer 8 and below. So if you're expecting to get usage from that browser, you can just rely on expires.

Example:

<script type="text/javascript">
function setMyCookie() {
   var now = new Date();
   var expires = new Date(now.setTime(now.getTime() + 60 * 60 * 1000)); //Expire in one hour
   document.cookie = 'n=1;path=/;expires='+expires.toGMTString()+';';
}
</script>

And your button can call this function like so:

<input type="button" onclick="setMyCookie();">Set Cookie</input>

Note that I've also included the path to indicate that this cookie is site-wide.

You can read more about expiring cookies with the date or max-age here: http://mrcoles.com/blog/cookies-max-age-vs-expires/

villecoder
  • 13,323
  • 2
  • 33
  • 52
  • This should probably be now.setTime(now.getTime() + 60 * 60 * 1000); //Expire in one hour document.cookie = 'n=1;path=/;expires='+now.toGMTString()+';'; } The value in expires is an integer; you want the updated Date in now – tgf Oct 29 '15 at 23:11
  • Thanks for the comment. I've updated the script to create a new Date object from now.setTime(). – villecoder Nov 02 '15 at 15:07
1

You can do:

onClick="setupCookie();"

function setupCookie() {
    document.cookie = "n=1";
    setTimeout(function() {
        document.cookie = "n=0";
    }, 3600000); // 1 hour
}
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • This would be dependent on the user staying on the site for an hour. If they navigate away from the page, the cookie's value will never be reset. – villecoder Sep 05 '13 at 14:02
0

On click you can call some javascript function and while creating cookie itself you can set expire time please refer this

javascript set cookie with expire time

Community
  • 1
  • 1
dharmesh
  • 308
  • 1
  • 13