...

View Full Version : Need help setting a cookie so the welcome box displays only ONCE



Mike Smith
06-02-2009, 02:51 AM
Hi everyone,

I am working with the "sexy alert box" found here (http://www.coders.me/web-html-js-css/javascript/sexy-alert-box-12-mootools-jquery) and have the code below, which pops up the sexy alert box on every page load.


<script type="text/javascript">
function test() {
Sexy.alert('Hello world!');
}
window.onload=test;
</script>

My problem is that I only want that code to show on the FIRST load for the user and every page after that it should not be showing. This will be the first time I've worked with cookies so I am a bit confused as to what to do with this code and where to edit things.

Any help I receive is greatly appreciated :)

Philip M
06-02-2009, 07:30 AM
Try this:-


<html>
<head>
<script type="text/javascript">
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);
}
</script>
</head>
<body>
<script type="text/javascript">
if(!readCookie('wroteIt')){
document.write('Your Message Goes Here And You See It Only Once');
createCookie('wroteIt', 'wroteIt', 365); // 365 days persistence
}
</script>
</body>
</html>

You could have found another example not a million miles from here at:-
http://www.javascriptkit.com/script/script2/alertmsg.shtml


“Expert: a man who makes three correct guesses consecutively.”
Dr. Laurence J. Peter (American "hierarchiologist", Educator and Writer, 1919-1990)

Mike Smith
06-02-2009, 04:24 PM
Philip - thanks.

I have a piece of code I've been working on but it's not working - any idea's why this wouldn't be working?


function firstVisit() {
var isFirstVisit = false;
if (!readCookie('firstVisit')) {
createCookie('firstVisit', 'true', 365);
isFirstVisit = true;
}
return isFirstVisit;
}
function test() {
if (firstVisit()) {
Sexy.alert('Hello world!');
}
}

window.onload=test;

adios
06-02-2009, 04:40 PM
<script type="text/javascript">

function addListener(obj, evt, handler)
{
if (obj.addEventListener)
{
obj.addEventListener(evt, handler, false);
}
else if (obj.attachEvent)
{
obj.attachEvent('on' + evt, handler);
}
}

addListener(window, 'load', function()
{
if (!/__BEENSEXY__/.test(window.name))
{
Sexy.alert('Hello world!');
window.name = '__BEENSEXY__';
}
}
);

</script>

Mike Smith
06-02-2009, 04:53 PM
adios - you're a genius! thank you so much :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum