On page load, if cookie set then hide div?

Hi there,

I’m not very good with Javascript so I need you help for page on my website…

Basically what I need to do is to make a DIV shown only first time someone visits page, and then when he/she revisit it I want that same DIV hidden, and I want it hidden for next 24 hours… so in that way DIV would be shown only once a day, and only on first page load.

So to make that happen I need to do fallowing, and I would need your help for that: I need a script that on a page load checks if cookie (which is 24h cookie) is set, if it is then it should hide that DIV, if it is not set then it should set it, so that DIV would be hidden on next page load…

Can someone help me with this, cause I am getting mad trying to do this whole day…

Thanks people!

Here is where you get the functions for handling cookies:
http://www.quirksmode.org/js/cookies.html


function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

The div to be shown should have a class name set to hide by default.


#advert {
   display: none;
}
#advert.show {
    display: block;
}

With the above cookie handling functions, you can use them like this:

Place the following script just before the </body> tag.


var days = 1;
var advert = document.getElementById('advert');
if (readCookie('seenAdvert')) {
    advert.className = '';
} else {
    advert.className = 'show';
    createCookie('seenAdvert', 'yes', days);
}