[SOLVED] Set cookie when button is clicked

I tried adding the set cookie DC in the url of a button in the hopes that that would result in setting the cookie only when the button is clicked. However, the cookie is already set when the page loads.

Is it possible to set a cookie when a button is clicked?

Hello @Dagaloni,

Thank you for the inquiry.

This is not possible by default, but you can still achieve this using the following features.

https://www.w3schools.com/jsref/event_onclick.asp
https://www.w3schools.com/js/js_cookies.asp

Add an onclick attribute to the button element, then refer to the cookie documentation for instructions on how to set a custom cookie.

If you’re interested, you can check out our One service.

Best regards,
Themeco

Thanks Ismael! I got it to work with JS.

Would be great if this could be done natively. It felt so intuitively to just add the set cookie DC in the url!

This is the code I used:

// Attach click handler
document
  .getElementById('YOUR_OBJECT_ID')
  .addEventListener('click', function() {
    // Compute expiration
    var expires = new Date(Date.now() + 86400 * 1000).toUTCString();
    // Set cookie
    document.cookie =
      'YOUR_COOKIE_NAME=YOUR_COOKIE_VALUE; expires=' + expires + ';';
  });

Thank you for your feedback. This is noted.