PDA

View Full Version : Function Run Once



Aidanx
06-15-2007, 11:40 AM
I am using an alert function to warn visitors to my site of expletive content and I want to set the javascript to run this alert only once. Tips?

Bob90
06-15-2007, 01:54 PM
Use cookies or PHP 'sessions'.

:)

There are many examples either in this forum or on the web.

Aidanx
06-15-2007, 06:13 PM
How do I set one up?

Twey
06-15-2007, 07:23 PM
You can also do it with Javascript:
if(typeof Twey === "undefined")
Twey = {
'GLOBAL' : this
};

Twey.Pythonic = {
'Array' : {
'filter' : function(f) {
for(var i = 0, r = []; i < this.length; ++i)
if((typeof f === "function" && f(this[i])) || (typeof f === "string" && this[i][f]))
r.push(this[i]);
return r;
},

'map' : function(f) {
for(var i = 0, r = []; i < this.length; ++i)
r.push(f(this[i]));
return r;
},

'reduce' : function(f) {
if(this.length === 0)
return null;
for(var i = 1, c = this[0]; i < this.length; ++i)
c = f(c, this[i]);
return c;
},
},

'LOAD' : function(n) {
var n = n.split("."),
o = n[0],
f = n[1];
return !!(
Twey.GLOBAL[o] &&
Twey.GLOBAL[o].prototype &&
typeof Twey.GLOBAL[o].prototype[f] === "undefined" &&
this[o] &&
this[o][f] &&
(Twey.GLOBAL[o].prototype[f] = this[o][f])
);
}
};

Twey.Pythonic.LOAD("Array.filter");
Twey.Pythonic.LOAD("Array.map");
Twey.Pythonic.LOAD("Array.reduce");

function Hash(kvals) {
for(var i = 0; i < kvals.length; ++i)
this[kvals[0]] = kvals[1];
}

Hash.prototype.toArray = function() {
var r = [];
for(var x in this)
if(this.hasOwnProperty(x))
r.push([x, this[x]]);
return r;
};

function cookieToHash(cookie) {
return new Hash(cookie.split(";").map(function(a) { return a.split("=").map(decodeURIComponent); }));
};

function hashToCookie(hash) {
return hash.toArray().map(function(a) { return a.map(encodeURIComponent).join("="); }).join(";");
};

onload = function() {
var hashBrown = cookieToHash(document.cookie);
if(!hashBrown['warned'])
if(!confirm("This site contains adult material. Are you sure you want to proceed?"))
location.replace("http://www.google.com/");
else {
hashBrown['warned'] = "yes";
document.cookie = hashToCookie(hashBrown);
}
}Note that users without Javascript won't be warned, though.

Bob90
06-17-2007, 08:51 AM
//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);
}


Just use these functions. Create a function that is called onload and checks the content of a cookie. like this.



if(readCookie('warning') !== 'warned')
{alert('There is some durty stuff on this site!')
createCookie('warning','warned',7)
}

alexjewell
06-17-2007, 06:19 PM
Twey, your scripts crack me up. Haha.

hashBrown? That's great.

Twey
06-17-2007, 08:33 PM
Just use these functions.I preferred mine. It's more verbose, but also neater, and the functions are quite reusable. It's a matter of taste, though.
Twey, your scripts crack me up. Haha.

hashBrown? That's great.All that talk of cookies and hashes made me hungry.

mwinter
06-17-2007, 09:46 PM
I preferred mine.

As far as I can see, it's defective (in a general sense) in that hashToCookie will collect all of the data, which is later simply assigned: session data must be set one datum at a time. The code also fails to set a lifetime, which seems to me to be a requirement for the OP.


If we're going to bandy implementations about, I'll include mine, below. Thus far, it's the only one to provide code to check for cookie support - people do disable them, you know!



var Session = function () {
var supported = false;

return {
get : function (name) {
var match = new RegExp('(^|;)\\s*' + name
+ '\\s*=\\s*([^\\s;]+)').exec(document.cookie);

return match ? match[2] : null;
},
set : function (name, value, maxAge, path, domain) {
var cookie = name + '=' + value;

if (typeof maxAge == 'number') {
var expires = new Date();

expires.setUTCSeconds(maxAge + expires.getUTCSeconds());
cookie += ';expires=' + expires.toGMTString();
}
if (typeof path == 'string') cookie += ';path=' + path;
if (typeof domain == 'string') cookie += ';domain=' + domain;
document.cookie = cookie;
},
remove : function (name, path, domain) {
this.set(name, 'deleted', -1, path, domain);
},
isSupported : function () {
if (typeof document.cookie == 'string') {
var name = 'test', value = 'fubar';

while (this.get(name) != null) name += name;
this.set(name, value);
if ((this.get(name) == value) && (this.get('expires') == null)) {
this.remove(name);
supported = (this.get(name) == null);
}
}
return (this.isSupported = function () {return supported;})();
},
makeAge : function (days, hours, minutes, seconds) {
return ((days * 24 + (+hours || 0)) * 60 + (+minutes || 0)) * 60 + (+seconds || 0);
}
};
}();

Date.prototype.toGMTString = function () {
var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov',
'Dec'];

return function () {
return days[this.getUTCDay()] + ', ' + this.getUTCDate().pad(2) + '-'
+ months[this.getUTCMonth()] + '-' + this.getUTCFullYear().pad(4) + ' '
+ this.getUTCHours().pad(2) + ':' + this.getUTCMinutes().pad(2) + ':'
+ this.getUTCSeconds().pad(2) + ' GMT';
};
}();

Number.prototype.pad = function (length, radix, character) {
return (+this).toString(+radix || 10).pad(length, character || '0');
};

String.prototype.pad = function (length, character) {
var result = String(this);
character = character || ' ';

while (result.length < length) result = character + result;
return result;
};

Twey
06-17-2007, 11:40 PM
As far as I can see, it's defective (in a general sense) in that hashToCookie will collect all of the data, which is later simply assigned: session data must be set one datum at a time.Could you elucidate on this a little? You're saying that it's wrong to simply assign a whole string and overwrite document.cookie?

mwinter
06-17-2007, 11:45 PM
You're saying that it's wrong to simply assign a whole string and overwrite document.cookie?

Yes. When reading, all session data is included separated by semicolons. However, if you have lots of session data to set, each name/value pair must be assigned individually. In the latter case, semicolons separate parameters, such as expiry date and applicable path, from the session data.

alexjewell
06-18-2007, 12:00 AM
It's a matter of taste, though.


Literally, Twey, I guess it is. =]