Javascript Notification Box Using Cookies to Remember Close

Due to the EU Cookie Directive that came into force in May 2012, any site that uses cookies, and assumes consent to drop these cookies, will need a notification on the site to inform the visitor that cookies are used, linking to a page that can give more information on how to remove them. 

Usually we just disable all unnecessary cookies so there is no need for this, but if you are using unnecessary cookies you will need to add a suitable notification. This method adds a subtle notification box at the bottom of the website, which when closed will use cookies to remember the choice for subsequent visits.

Note: the user will require Javascript enabled for this to work. Ideally you should modify this script to show the message even with Javascript disabled

First, add the Javascript. We add this to our global JS file with our document.ready() call:

$(document).ready(function()
{
    /******************
    COOKIE NOTICE
    ******************/
    if(getCookie('show_cookie_message') != 'no')
    {
        $('#cookie_box').show();
    }

    $('.cookie_box_close').click(function()
    {
        $('#cookie_box').animate({opacity:0 }, "slow");
        setCookie('show_cookie_message','no');
        return false;
    });
});

function setCookie(cookie_name, value)
{
    var exdate = new Date();
exdate.setDate(exdate.getDate() + (365*25));
document.cookie = cookie_name + "=" + escape(value) + "; expires="+exdate.toUTCString() + "; path=/"; } function getCookie(cookie_name) { if (document.cookie.length>0) { cookie_start = document.cookie.indexOf(cookie_name + "="); if (cookie_start != -1) { cookie_start = cookie_start + cookie_name.length+1; cookie_end = document.cookie.indexOf(";",cookie_start); if (cookie_end == -1) { cookie_end = document.cookie.length; } return unescape(document.cookie.substring(cookie_start,cookie_end)); } } return ""; }

Secondly add the relevant styles to your stylesheet, which styles the box and fixes it at the bottom of the page:

/***************************
COOKIE BOX
***************************/
#cookie_box
{ 
	position: fixed;
	display: none;
	bottom: 0px;
	font-size: 0.8em;
	z-index: 1000;
	background:#393939;
	padding:5px;
	text-align:center;
	width:99%;
	color:#ffffff;
}
	#cookie_box a:hover
	{ 
		color:#ffffff;
		text-decoration: underline
	}

Lastly, add the relevant HTML to the page to show the notification box, your message, and the close button:

<div id="cookie_box">Our site requires cookies to function, <a href="/cookies">click here</a> for more information <a href="#" class="cookie_box_close">Close [X]</a></div>