Ben
Ben

Reputation: 2564

Javascript set cookie expire time on button click

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?

Upvotes: 1

Views: 5995

Answers (3)

villecoder
villecoder

Reputation: 13483

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/

Upvotes: 3

dharmesh
dharmesh

Reputation: 308

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

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

You can do:

onClick="setupCookie();"

function setupCookie() {
    document.cookie = "n=1";
    setTimeout(function() {
        document.cookie = "n=0";
    }, 3600000); // 1 hour
}

Upvotes: 1

Related Questions