Page 1 of 2 12 LastLast
Results 1 to 10 of 11

Thread: Function Run Once

  1. #1
    Join Date
    Mar 2007
    Location
    Scotland
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Function Run Once

    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?

  2. #2
    Join Date
    Feb 2007
    Location
    England
    Posts
    254
    Thanks
    0
    Thanked 5 Times in 5 Posts

    Default

    Use cookies or PHP 'sessions'.



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

  3. #3
    Join Date
    Mar 2007
    Location
    Scotland
    Posts
    18
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    How do I set one up?

  4. #4
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    You can also do it with Javascript:
    Code:
    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.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  5. #5
    Join Date
    Feb 2007
    Location
    England
    Posts
    254
    Thanks
    0
    Thanked 5 Times in 5 Posts

    Default

    Code:
    //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.

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

  6. #6
    Join Date
    Mar 2006
    Location
    Cleveland, Ohio
    Posts
    574
    Thanks
    6
    Thanked 5 Times in 5 Posts

    Default

    Twey, your scripts crack me up. Haha.

    hashBrown? That's great.
    Thou com'st in such a questionable shape
    Hamlet, Act 1, Scene 4

  7. #7
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    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.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  8. #8
    Join Date
    Dec 2004
    Location
    UK
    Posts
    2,358
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by Twey View Post
    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!

    Code:
    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;
    };
    Mike

  9. #9
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    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?
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  10. #10
    Join Date
    Dec 2004
    Location
    UK
    Posts
    2,358
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by Twey View Post
    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.
    Mike

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •