DEAL ENDS IN:

SPRING SALE!

UP TO 35% OFF!

GET IT NOW

How can I add a cookie on click using HTML?

The following code creates a button that adds a cookie with the name ‘test-cookie-on click’ and the value ‘clicked’ when clicked.

This code can be applied to any HTML element.

The cookie duration in this code is 307584000000 seconds (365 days). Feel free to change the value to fit your requirements.

<button onclick="
  let cookieName = 'test-cookie-on click'
  let cookieValue = 'clicked'
  let cookieExpireTime = 307584000000

  setCookie(cookieName, cookieValue, cookieExpireTime)

  function setCookie(name,value,time) {
    var expires = ''
    if (time) {
      var date = new Date()
      date.setTime(date.getTime() + time)
      expires = '; expires=' + date.toUTCString()
    }
    document.cookie = name + '=' + (value || '')  + expires + '; path=/'
  }
">
  Add a Cookie
</button>

Result: