Results 1 to 9 of 9

Thread: Generally Useful Javascript Functions..Thread

  1. #1
    Join Date
    Sep 2008
    Posts
    119
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Lightbulb Generally Useful Javascript Functions..Thread

    Hopefully this will be made a sticky someday, but I feel it'd be nice to start a thread of normal every day useful javascript functions that people forget sometimes (guilty).


    This is a Basic Javascript Checkbox Validation script... They used to bug the crap out of me.

    Code:
    <input onclick="checkthebox();" type="checkbox" name="music" id="music" value="checkbox">
    <script>
    function checkthebox() 
    {if(document.getElementById('music').checked)
    {alert('you checked it!');} else {alert('please check the checkbox');}}
    </script>

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

    Default

    Code:
    var Format = (function() {
      function interpolate(s, o) {
        s = s.replace(/\[\[/g, '\0');
        for (var x in o)
          if (o.hasOwnProperty(x))
            s = s.replace(new RegExp('\\[' + x + '\\]', 'g'), o[x]);
        return s;
      }
    
      return {
        interpolate: interpolate
      };
    })();
    
    var Functions = (function() {
      var O = {
        lookup: function(a, i) {
          return a[i];
        },
    
        equals: function(a, b) {
          return a === b;
        }
      };
    
      var F = {
        bind: function(obj, fun, args) {
          return function() {
            if (obj === true)
              obj = this;
    
            var f = typeof fun === "string" ? obj[fun] : fun;
    
            return f.apply(obj, Array.prototype.slice.call(args || [])
                .concat(Array.prototype.slice.call(arguments)));
          };
        },
    
        compose: function(/* f1 [, f2 [, ... [, fn]]] */) {
          var fs = Array.prototype.slice.call(arguments);
    
          return function() {
            var args = Array.prototype.slice.call(arguments);
    
            for (var i = fs.length - 1; i >= 0; --i)
              args.unshift(fs[i].apply(this, args));
    
            return args[0];
          };
        },
    
        reorder: function(f, ord) {
          return function() {
            var oldargs = Array.prototype.slice.call(arguments);
    
            return f.apply(this, F.map(function(v) { return oldargs[v]; }, ord));
          };
        },
    
        flip: function(f) {
          return F.reorder(f, [1, 0]);
        },
    
        curry: function(f, l, a) {
          l = (typeof l === "number" ? l : (f.length || 0));
          a = a || [];
    
          return function() {
            var m = a.concat(Array.prototype.slice.call(arguments));
            return m.length < l ? Functional.curry(f, l, m) : f.apply(this, m);
          };
        },
    
        Operators: O
      };
    
      return F;
    })();
    
    var Lists = {
      map: function(f, a) {
        for (var i = a.length - 1, r = []; i >= 0; --i)
          r[i] = f(a[i], i);
    
        return r;
      },
    
      reduce: function(f, t, a) {
        for (var i = 0, n = a.length; i < n; ++i)
          t = f(t, a[i]);
        return t;
      },
    
      filter: function(f, a) {
        for (var i = 0, r = [], n = a.length; i < n; ++i)
          if (f(a[i], i))
            r[r.length] = a[i];
    
        return r;
      }
    };
    
    var using = (function() {
      var extensions = {}, global = this;
    
      function isApplied(extn) {
        var e = extn.split('.');
        return extensions[e[0]][e[1]] && global[e[0]].prototype[e[1]];
      }
    
      function apply(extn) {
        var e = extn.split('.');
        return global[e[0]].prototype[e[1]] = extensions[e[0]][e[1]];
      }
    
      function unapply(extn) {
        var e = extn.split('.');
        delete global[e[0]].prototype[e[1]];
      }
    
      function using() {
        var extns = Array.prototype.slice.call(arguments);
        return function(fn) {
          return function() {
            for (var i = extns.length; --i >= 0; )
              if (!isApplied(extns[i]))
                apply(extns[i]);
              else
                extns.splice(i, 1);
    
            var r = fn.apply(this, Array.prototype.slice.call(arguments));
    
            for (var i = extns.length; --i >= 0; )
              unapply(extns[i]);
    
            return r;
          };
        };
      }
    
      function add(c, o) {
        for (var x in o)
          if (o.hasOwnProperty(x))
            (extensions[c] || (extensions[c] = {}))[x] = o[x];
        return o;
      }
    
      function get() {
        return extensions;
      }
    
      using.add = add;
      using.get = get;
    
      return using;
    })();
    
    var Generic = (function() {
      var MATCH_FAIL = {},
          MATCH_ANY  = {};
    
      function create(fallback) {
        var s = function() {
          for (var i = 0, args = Array.prototype.slice.call(arguments), r; i < specs.length; ++i)
            if ((r = specs[i].match(args)) !== MATCH_FAIL)
              return r;
    
          if (s._fallback)
            return s._fallback.apply(this, args);
    
          throw new Error("Generic: No methods matched and no fallback provided.");
        }, specs = s._specs = [];
    
        s.specialise = specialise;
        s.addFallback = addFallback;
        if (fallback)
          s.addFallback(fallback);
    
        return s;
      }
    
      function specialise(patterns, func) {
        var s = this._specs;
    
        s[s.length] = new Specialisation(patterns, func, this);
    
        return this;
      }
    
      function addFallback(func) {
        this._fallback = func;
    
        return this;
      }
    
      /**** Begin Specialisation ****/
    
      function Specialisation(patterns, func, context) {
        this.patterns = patterns;
        this.func = func;
        this.context = context;
      }
    
      Specialisation.compatible = function(value, pattern) {
        if (pattern === MATCH_ANY && value !== undefined)
          return true;
        else if ((typeof pattern === "string" || pattern instanceof String) && typeof value === pattern)
          return true;
        else if ((typeof pattern === "function" || pattern instanceof Function) && value instanceof pattern)
          return true;
        else if (pattern instanceof Pattern)
          return pattern.guard(value);
        else if (pattern instanceof Interface)
          return pattern.match(value);
    
        return false;
      };
    
      Specialisation.prototype = {
        match: function(args) {
          for (var i = 0, a = this.patterns, n = a.length; i < n; ++i)
            if (!Specialisation.compatible(args[i], a[i]))
              return MATCH_FAIL;
    
          return this.func.apply(this.context, args);
        }
      };
    
      /**** Begin Pattern ****/
    
      function Pattern(guard) {
        this.guard = guard;
      }
    
      function GUARD(func) {
        return new Pattern(func);
      }
    
      function GUARD_IS(right) {
        return new Pattern(function(val) {
          return val === right;
        });
      }
    
      /**** Begin Interface ****/
    
      function Interface(obj) {
        if (!(this instanceof Interface))
          return new Interface(obj);
    
        for (var x in obj)
          if (obj.hasOwnProperty(x))
            this[x] = obj[x];
      }
    
      Interface.getSkeleton = function(obj) {
        var r = {};
    
        for (var x in obj)
          if (obj.hasOwnProperty(x))
            r[x] = typeof obj[x];
    
        return new Interface(r);
      };
    
      Interface.prototype = {
        match: function(value) {
          for (var x in this)
            if (this.hasOwnProperty(x) && !Specialisation.compatible(value[x], this[x]))
              return false;
    
          return true;
        }
      };
    
      return {
        create: create,
        Interface: Interface,
        GUARD: GUARD,
        GUARD_IS: GUARD_IS,
        MATCH_ANY: MATCH_ANY
      };
    })();
    I'm sure I could think of some more (noticeably, my zip() function is missing... anyone know where that got to?). I'd quite like to include my Javascript cells implementation, which is very handy, but is also, I think, on my other harddrive, which is in a defunct machine.
    Last edited by Twey; 10-10-2008 at 06:53 AM.
    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!

  3. #3
    Join Date
    Sep 2008
    Posts
    119
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default

    This is a very short tabbed content script I came up with recently while dinkin around. It uses html colors, but is easily modifiable to support image change out if needed. Also supports a "default tab loaded" function. Small in size, which is nice. I'd like to see how small this script could be... could be fun. Looks like butt in Firefox right now too.

    Code:
    <head>
    <style type="text/css">
    .selecttabs{cursor:pointer;background-color:#cccccc;background-repeat:no-repeat;display:inline;width:96px;height:22px;margin-right:3px;text-align:center;}
    .selectcontent{width:100%;border:1px solid #cccccc;padding:5px;height:300px;list-style-type:none;}
    </style>
    <script type="text/javascript">
    function defload()
    {
    // Set the default tab you want loaded next line down.
    Default_Tab_Loaded = '2';
    calldef = document.getElementById(Default_Tab_Loaded);
    document.getElementById(Default_Tab_Loaded).id = 'selected';document.getElementById('selected').style.backgroundColor = '#ffff00';
    document.getElementById(calldef.title + '_content').style.display = '';document.getElementById('selected').id = Default_Tab_Loaded;
    }
    function tabber()
    {var divs = document.frmMain.getElementsByTagName('div');
    for(var i = 0; i < divs.length; i++)
    {if (divs[i].id=='selected') 
    {divs[i].style.backgroundColor = '#ffff00';document.getElementById(divs[i].title + '_content').style.display = '';}
    else 
    {divs[i].style.backgroundColor = '#cccccc';document.getElementById(divs[i].title + '_content').style.display = 'none';}}}
    </script>
    </head>
    <body onload="defload();">
    <form style="margin-bottom:0px;" id="frmMain" name="frmMain">
    <div class="selecttabs" onclick="this.id = 'selected';tabber();this.id='1'" id="1" name="1" title="hats"/>one</div>
    <div class="selecttabs" onclick="this.id = 'selected';tabber();this.id='2'" id="2" name="2" title="shirts"/>two</div>
    <div class="selecttabs" onclick="this.id = 'selected';tabber();this.id='3'" id="3" name="3" title="cars">three</div>
    <div class="selecttabs" onclick="this.id = 'selected';tabber();this.id='4'" id="4" name="4" title="chess">four</div>
    
    <ul style="width:400px;height:400px;list-style-type:none;margin:0px;">
    <!-- Next down is where you have your content. -->
    <li id="hats_content" style="display:none;" class="selectcontent">content1</li>
    <li id="shirts_content" style="display:none;" class="selectcontent">shirts</li>
    <li id="cars_content" style="display:none;" class="selectcontent">content3</li>
    <li id="chess_content" style="display:none;" class="selectcontent">content4</li>
    </ul>
    </form>
    </body>
    </html>
    Last edited by Falkon303; 10-10-2008 at 02:34 AM.

  4. #4
    Join Date
    Sep 2008
    Posts
    119
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Get Vertical scrollbar location of a div (overflow) layer

    This is a simple way to get, and now set the vertical and horizontal scroll location of a div layer.

    Code:
    <body onload="document.getElementById('huh').scrollTop = '20';document.getElementById('huh').scrollLeft = '10';">
    <div id="read" name="read"></div>
    <div id="huh" name="huh" onmousemove="document.getElementById('read').innerHTML = 'y: ' + this.scrollTop + '  x: ' + this.scrollLeft;" style="width:300px;height:450px;overflow:auto;border:1px solid #cccccc;">
    <img src="http://i2.photobucket.com/albums/y21/steviepot/cheeseburger_helmit.jpg">
    </div>
    </body>
    Last edited by Falkon303; 10-10-2008 at 11:35 PM. Reason: Now includes setting x and y as well. Dopeness.

  5. #5
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Quote Originally Posted by Twey View Post
    Code:
    var Format = (function() {
      function interpolate(s, o) {
        s = s.replace(/\[\[/g, '\0');
        for (var x in o)
          if (o.hasOwnProp . . .
                     . . . nterface,
        GUARD: GUARD,
        GUARD_IS: GUARD_IS,
        MATCH_ANY: MATCH_ANY
      };
    })();
    I'm sure I could think of some more (noticeably, my zip() function is missing... anyone know where that got to?). I'd quite like to include my Javascript cells implementation, which is very handy, but is also, I think, on my other harddrive, which is in a defunct machine.
    The prototwey.js library? Perhaps tweyQuery?
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

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

    Default

    Much smaller, no weird interdependencies Just a few handy functions.

    I'm seeing a lot of bad code here, folks. Remember, innerHTML is proprietary, leads to bad design, and has some weird effects and bugs. Stay away from it — you can do anything you need to with the DOM methods, unless you're actually accepting HTML as input from the user (a pretty rare scenario). Also, don't forget to keep your code valid.
    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!

  7. #7
    Join Date
    Sep 2008
    Posts
    119
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by Twey View Post
    Much smaller, no weird interdependencies Just a few handy functions.

    I'm seeing a lot of bad code here, folks. Remember, innerHTML is proprietary, leads to bad design, and has some weird effects and bugs. Stay away from it — you can do anything you need to with the DOM methods, unless you're actually accepting HTML as input from the user (a pretty rare scenario). Also, don't forget to keep your code valid.

    Could you expand on this for me? I am interested, just unaware due to browsing and learning that way. I'd really appreciate it if you could provide me with a very basic example.

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

    Default

    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!

  9. The Following User Says Thank You to Twey For This Useful Post:

    Falkon303 (10-11-2008)

  10. #9
    Join Date
    Sep 2008
    Posts
    119
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default

    Very useful.. I did some reading last night about this. Although the efficiency is a tiny bit hurt when using DOM, it seems that the compatibility and validation/standardization of the program is set in stone.

    I read a few article on this, and the majority of people supported .innerHTML, although for enterprise/professional, it was DOM or bust.

    I'll keep my mouth shut on useful script until I know the DOM, as to not mislead peeps.
    Thanks for this..... further up the mountain we go!

    What about the idea of creating an innerHTML to DOM conversion proggy?

    Not for loading of course, but rather as a translator. Any thoughts?
    Last edited by Falkon303; 10-11-2008 at 08:53 PM.

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
  •