Hide cookie banner for a year

Marko Krstić
9 Jun 2022

Use JavaScript to hide element for one year. It’s perfect for banners such as cookie. You can easily change parameters and change it from 365 days to what ever you need.

// Key under which name the cookie is saved
const cookieName = 'cookieconsent';
// The value could be used to store different levels of consent
const cookieValue = 'dismissed';

function dismiss() {
    const date = new Date();
    // Cookie is valid 1 year: now + (days x hours x minutes x seconds x milliseconds)
    date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000));
    // Set cookie
    document.cookie = `${cookieName}=${cookieValue};expires=${date.toUTCString()};path=/`;

    // You probably want to remove the banner
    document.querySelector('.editors-note').remove();
}

// Get button element
const buttonElement = document.querySelector('.element-dismiss');
// Maybe cookie consent is not present
if (buttonElement) {
    // Listen on button click
    buttonElement.addEventListener('click', dismiss);
}

Your element need to have class of “element-dismiss” and you need to place button element inside


<div class="element-dismiss cookie-baner">
    <h3>Cookie Banner</h3>    
    <p>DPlugins collects and stores your information to better customize your site experience and to optimize our website. However, your consent is required before we can provide this free service.<p> 
    <a class="read-more" href="https://code.dplugins.com/privacy-policy/">Privacy Policy</a>
    <button class="btn-dismiss">Accept</button>
</div>

Was this article helpful?

Tags

Categories

Never miss new post again

Subscribe and get list of new posts in your inbox

Click to Copy