Set a JavaScript Cookie

Posted on Mar 26, 2025

by Jimmy


Basic example of how to create a JavaScript cookie.

JavaScript
        
            document.cookie = 'alert=alert_dismissed; max-age=3600; path=/';        
    

Example of cookie usage in a pop-up to ensure it doesn't open again after user interaction

JavaScript
        
            const initPopUp = () => {
    // Guard: if no popup on page, exit the function
    if(!document.querySelector(".popup")) return;
    const popup = document.querySelector('.popup');
    const close = popup.querySelectorAll('.close-popup');

    close.forEach( (e) => {
        e.addEventListener('click', () => {
            popup.classList.add('remove-popup');
            document.cookie = 'alert=alert_dismissed; max-age=1800; path=/';
        })
    });
}        
    

Execute the function after the DOM is finished loading

JavaScript
        
            window.addEventListener("DOMContentLoaded", () => {
  initPopUp();
});        
    

Documentation

MDN Web Docs


Back to Snippets