Show a cookie policy notice on first site visit

Sites in various parts of the world, for example the UK, need to display information to visitors about their use of cookies. This is typically done with a cookie information page and a notice which appears on a user’s first visit to the site.

Many sites store the fact that a user has seen the notice about cookies with a cookie. We’re going to look at a way of doing this.

First, you need a bit of HTML with your warning (example text only). Choose a suitable id.

<div id="cookie-notice" class="hidden">
    We use cookies...
</div>

The default .hidden class should look like:

.hidden {
    display: none;
    visibility: hidden;
}

Style the element as necessary.

#cookie-notice {
    margin: 1em 0;
    padding: 1em;
    border: 1em solid lightblue;
    background-color: white;
    color: #888;
}

This should give us (without the .hidden class):

Now for the javascript.

(function () {
    /* Check for our cookie, if present do nothing, 
     * otherwise show the cookie notice and set the
     *  cookie. */
    if (null === (document.cookie + ';').match(/cookieseen=yes;/)) {

        /* Replace the `.hidden` class via the `id`
         * set on the HTML. */
        document.getElementById("cookie-notice").className="active";
        var d = new Date();

        /* 90 days */
        d.setTime(d.getTime()+(90*86400000));

        /* Set the cookie. */
        document.cookie = "cookieseen=yes; expires="+d.toGMTString()+"; path=/";
    }
})();

Read more

For further information see:

Tags: