working on it ...

Filters

Explore Public Snippets

Sort by

Found 79 snippets

    public by JKCPR  465  1  5  1

    is your DOM classy? Wouldn't your console like to know...

    Intended as Dev Tool to be utilised in the browser console so that refactoring your messy CSS can be less hurty.
    ;( 
      function (){
      "use strict";
    
      //get ALL DOM elements => BODY > *, BODY *
      var elms = document.body.getElementsByTagName("*"),
          i = elms.length,
          arr = [],
          classArray;
      
      //iterate, isolate, finally indicate
      while( i-- ) {
          classArray = elms[i].className.split(/\s+/);
          if (classArray.length > 1) {
              arr.push( classArray[1] );
          }
      }
      
      console.log( arr.join(',') );
      return arr;
      
    })();

    public by zer00ne  2665  4  5  0

    Single Event Handler for Multiple Elements

    addEventListener to an ancestor element of multiple descendant elements
    /*
    HTML should comprise of a group of elements intended 
    to be clicked or any other event trigged by user interaction.
    The parentSelector parameter is any working selector to
    reference an element that is an ancestor to that group of
    elements.
    EX.
    <section id="perentEle">
      <a href="#" id='link1'>Link 1</a>
      <a href="#" id='link2'>Link 2</a>
      <a href="#" id='link3'>Link 3</a>
    </section>
    */
    var parentEle = document.querySelector(parentSelector);
    
    parentEle.addEventListener('click', testFunc, false);
    
    function testFunc(event) {
      event.preventDefault();
      if(event.target !== target.currentTarget) {
        var clickedChild = event.target.id;
        var child = document.getElementById(clickedChild);
        alert('ID: ' + child.id);
      }
      event.stopPropagation();
    }

    public by sTiLL-iLL @ SniPitz-KND  5151  4  9  42

    Vanilla KemPlates... MVC in stiches....

    real kwik model view controller example made with 100% vanilla JS
    
    ///  MY "SIGNALS" EVENT SYSTEM ////////////////
    
    //   this solution Uses my signals.js module
    
    ////////  styles  ///////////
    
    
    body {
    	font-family: Calibri;
    	width: 220px;
    }
    
    .container {
        border: 1px solid black;
        padding: 10px;
        width: 232px;
        margin: 50px auto 50px 350px;
    	border-radius: 7px;
    	background: lightgray;
    }
    
    fieldset {
    	width: 205px;
    	margin: 0 auto 3px 3px;
    	margin-right: auto;
    	margin-bottom: 6px;
    	padding: 10px;
    }
    
    h1 {
    	margin-left: 55px;
    	margin-right: auto;
    }
    
    span {
    	margin: 3px;
    }
    
    input {
    	margin-top: 2px;
    	margin-bottom: 8px;
    	width: 168px;
    	padding-left: 3px;
    }
    
    ul {
    	padding-left: 20px;
    	list-style: none;
    	color: navy;
    	overflow-x: hidden;
    }
    
    li {
    	max-width: 180px
    }
    
    
    
    /////////  Model(s)   ////////////////////////
    
    // this is the user model object
    
    var user1 = {
        name1: "Richard",
        name2: "Longwood",
        occupation: "Software Engineer",
        age: "40",
        title: 'Skillz Yo!',
        subTitle: "add a skill...",
        showSkills: true,
        skills: []
    };
    
    
    
    function UserModel (usr) {
        this.user = usr;
        this.get = function(k) {
            if (k) {
                var u = this.user;
                return u[k];
            } 
            else {
                var u = this.user;
                return u;
            }
        };
    };
    
    
    
    var User = new UserModel (user1);
    User.prototype = Signals;
    User.constructor = User;
    
    User.on = function(v, cbk) {
        this.prototype.receive(v, function(d) {
            cbk.call(this.user, d);
        });
    };
    User.emit = function(v) {
        this.prototype.signal("change", v);
    };
    User.off = function(v) {
        this.prototype.dropReceivers(v);
    };
    User.set = function(k, v) {
        if (v && v !== this.user[k]) {
            if (k == "skills") {
                this.user[k].push(v);
            } else {
                this.user[k] = v;
            }
            this.prototype.signal("change", this.user);
        }
    };
    
    
    
    // array for template strings, 
    // our template engine, and an array of target Ids.
    
    var kList = [], 
        TPE = new TPEngine(), 
        Nodz = ["t1", "t2", "t3", "t4", "t5", "t6"];
    
    
    
    // this template string is pretty bulky, 
    // so Ill keep it stashed as a string, 
    // then inject it into its target when its time.
    
    var template6 = '~>{ if(User.get("showSkills")) { :}' + 
            '~>{ for(var index in User.get("skills")) { :}' + 
            '<li><a href="#"> ~>{ User.get("skills")[index] :}' + 
            '</a></li> ~>{ } :}' + '~>{ } else { :}' + 
            '<li>none</li>' + '~>{ } :}';
    
    
    
    // this array holds the template strings.
    // the innerText is where I extract them from the mark-up
    // notice how #5 is already defined
    
    var Templates = [
        template1 = t1.innerText, 
        template2 = t2.innerText, 
        template3 = t3.innerText, 
        template4 = t4.innerText,
        template5 = t5.innerText, 
        template6
    ];
    
    
    // Now I iterate over the list of nodes and templates,
    // pull each one out per the array position and plug
    // them into the kompiler along with the property of the node that 
    // the content is assigned to, then komile into a "kPlate" template.
    // each one of these kPlates is then put into another array: "kList"
    
    Nodz.forEach(function(tmpltNd) {
        var seed = Templates.shift();
        kPlt = TPE.Template(tmpltNd, "innerHTML", seed);
        kList.push(kPlt);
    });
    
    
    
    // Here, we set up the 2-way bindings
    
    var bb = document.getElementById("btn"), 
        tgl = document.getElementById("tgl"),
        updateDom = function (d) {
            kList.forEach(function(itm) {
                TPE.BindSet(itm, d);
            });
        },
        updateModel = function (d) {
            User.set("skills", tgl.value);
            tgl.value = "";
        };
    
    
    // When the button is pressed, this handler
    // in the controller hears it, grabs the new value
    // and updates the model.
    
    bb.addEventListener("click", updateModel);
    
    
    // When the model's value is changed, it fires a change event.
    // The handler here in the controller hears it,
    // grabs the new value, and then updates the dom
     
    User.on("change", updateDom);
    
    
    // This part basicly is what runs on window ready.
    // Now that everything is all set up..
    // we iterate over the array of kPlates that we stored earlier,
    // calling BindSet on each one. This renders the mark-up
    // to the dom at lightening speed, and there ya go!
    
    kList.forEach(function(itm) {
        TPE.BindSet(itm, User);
    });
    
    
    
    
    
    
    //////////// Template kompiler (controller)  //////////////////////////////////////
    
    this.TPEngine = function() {
        var kompiler = function(templateString, model) {
            var rgx = /~>{([^:]+)?:}/g, 
            rgex = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g, 
            segment = 'var r=[];\n', position = 0, 
            kompile = function(chunk, ixjs) {
                ixjs ? (segment += chunk.match(rgex) ? chunk + '\n' : 'r.push(' + chunk + ');\n') : 
                (segment += chunk != '' ? 'r.push("' + chunk.replace(/"/g, '\\"') + '");\n' : '');
                return kompile;
            };
            while (match = rgx.exec(templateString)) {
                kompile(templateString.slice(position, match.index))(match[1], true);
                position = (match.index + match[0].length);
            }
            ;
            kompile(templateString.substr(position, templateString.length - position));
            segment += 'return r.join("");';
            return new Function(segment.replace(/[\r\t\n]/g, '')).apply(model);
        }, 
        template = function(elementID, prop, templateString) {
            var c = {
                tStr: templateString,
                tProp: prop,
                tVal: document.getElementById(elementID)
            };
            return c;
        }, 
        applyBind = function(temp, model) {
            if (temp.tVal.id && temp.tStr && model) {
                template = temp;
                var el = document.getElementById(template.tVal.id);
                el[template.tProp] = kompiler(template.tStr, model);
                template.tVal = el;
            }
        };
        return {
            Template: template,
            BindSet: applyBind
        };
    };
    
    
    ///////// VIEW  //////////////////////////
    
    <!DOCTYPE html>
    <html>
    <head>
    	<title>MY MVC</title>
    </head>
      	<meta charset="utf-8" />
    	<link rel="stylesheet" href="css/stylz.css" />
    	<script src="js/signals.js"></script>
    	<script src="js/myTPlates.js"></script>
    <body>
    	<div class="container">
    		<h1 id="t1">
    			~>{ User.get("title") :} 
    		</h1>
    		<fieldset>
    			<legend id="t2">
    				~>{ User.get("subTitle") :}
    			</legend>
    			<input id="tgl" type="text" placeholder="skills"></input>
            	<button id="btn">+</button>
    			<hr><b>
    			  Name:
    			  <span id="t3">
    					~>{ User.get("name1") +" "+ User.get("name2") :}
    			  </span>
    			  </br>
    			  Age: 
    			  <span id="t4">
    					~>{ User.get("age") :}
    			 </span>
    			 </br>
    			  Dept: 
    			  <span id="t5">
    					~>{ User.get("occupation") :}
    			 </span>
    			 <hr>
    			  Skills List: 
    			 <ul id="t6">
    					~>{ User.get("skills") :}
    			 </ul></b>	
    			<hr>
    		</fieldset>
    	</div>
    </body>
    <script src="js/script1.js"></script>
    </html>
    
    
                                                                                                                

    public by sTiLL-iLL @ SniPitz-KND  4063  3  7  18

    mark out your sites, this labels the most visited link from your browser!

    get MVLinkage.js
    //  this makes a "most visited" link element.  //
    //-------------------------------------------------//
      
    function spawnMVLink(params, href, title, text, direction, provider) {
      
      var styles = getMostVisitedStyles(params, !!text),
          link = document.createElement('a');
          link.style.color = styles.color;
          link.style.fontSize = styles.fontSize + 'px';
          
      if (styles.fontFamily) {
          link.style.fontFamily = styles.fontFamily;
        }
        
      if (styles.textAlign) {
          link.style.textAlign = styles.textAlign;
        }
        
      if (styles.textFadePos) {
        var dir = /^rtl$/i.test(direction) ? 'to left' : 'to right';
        var mask = 'linear-gradient(' + dir + ', rgba(0,0,0,1),' +
            'rgba(0,0,0,1) ' + styles.textFadePos + 'px, rgba(0,0,0,0))';
            
        link.style.textOverflow = 'clip';
        link.style.webkitMask = mask;
      }
      
      link.href = href;
      link.title = title;
      link.target = 'top';
      link.tabIndex = '0';
      
      if (text) { 
        link.textContent = text;
      }
      link.addEventListener('focus', function() {
        window.parent.postMessage('linkFocused', DOMAIN_ORIGIN);
      });
      
      link.addEventListener('blur', function() {
        window.parent.postMessage('linkBlurred', DOMAIN_ORIGIN);
      });
      
      var navigate = function doNav(e) {
        
        var isFrmSrvr = 'url' in params;
        if (isFrmSrvr && params.ping) {
          ping(DOMAIN_ORIGIN + params.ping);
        }
        
        var handle = location;
        if ('pos' in params && isFinite(params.pos)) {
          handle.logMV(parseInt(params.pos, 10), provider || '');
        }
        
        if (!isFrmSrvr) {
          e.preventDefault();
          handle.navigateContentWindow(href, getEventDisposition(e));
        }
      };
      
      link.addEventListener('click', navigateFunction);
      
      link.addEventListener('keydown', function(event) {
          if (event.keyCode == 46 || event.keyCode == 8 ) {
            event.preventDefault();
            window.parent.postMessage('tileBlacklisted,' + params.pos, DOMAIN_ORIGIN);
          } 
          else if (event.keyCode == 13 || event.keyCode == 32 ) {
            navigate(event);
          }
      });
      return link;
    }            

    public by sTiLL-iLL @ SniPitz-KND  3765  4  8  19

    object data store... stuff it in yer client

    make a data tier in the browser
    
      // Local Data
       
    function DB(store, schema) {
          this.store = store;
          if (!localStorage[store] || typeof localStorage[store] == 'undefined') {
              localStorage[store] = JSON.stringify(schema|| {});
          }
          this.setData = function (key, val) {
              var lda = JSON.parse(localStorage[this.store]);
              doUpdate(ldta, key, val);
              localStorage[store] = JSON.stringify(ldta);
          };
          this.getData = function (key) {
              var ldta = JSON.parse(localStorage[this.store]);
              if (key) {
                  return pathGet(ldta, key);
              }
              return ldta;
          };
          this.reset = function (schema) {
              localStorage[this.store] = JSON.stringify(schema || {});
          };
          this.delete = function() {
              localStorage.removeItem(this.store);
          };
          var doUpdate = function (ob, kStr, val) {
              var kpth = keyStr.split('.'),
              i = 0, lstIdx = kpth.length - 1;
              for (;i < lstIdx; ++i) {
                  var key = kpth[i];
                  if (!(key in ob)) {
                      ob[key] = {};
                  }
                  ob = ob[key];
              }
              ob[kpth[lstIdx]] = val;
          };
          var pathGet = function (obj, key, leftOvrs) {
              if ( leftOvrs === undefined ) {
                  leftOvrs = key.split('.');
              }
              var cur = leftOvrs.shift();
              if ( typeof(obj) == 'object' && obj[cur] !== undefined ) {
                  if ( leftOvrs.length === 0 ) {
                      return obj[cur];
                  }
                  else if ( typeof(obj[cur]) == 'object' ) {
                      return arguments.callee(obj[cur], undefined, leftOvrs);
                  }
              }
              return null;
          };
      }
                

    public by sTiLL-iLL @ SniPitz-KND  4162  2  7  19

    Try this HashMap! ++ ++ ++

    hash-table and key generator,.. uuids, cool extedo method, oh yeah, it also supports using objects as keys!!!
    ///////////////////////////
    // unique ids puhleez!!! //
    ///////////////////////////
    
    function nextUid() {
      var index = uid.length;
      var digit;
    
      while(index) {
        index--;
        digit = uid[index].charCodeAt(0);
        if (digit == 57 /*'9'*/) {
          uid[index] = 'A';
          return uid.join('');
        }
        if (digit == 90  /*'Z'*/) {
          uid[index] = '0';
        } else {
          uid[index] = String.fromCharCode(digit + 1);
          return uid.join('');
        }
      }
      uid.unshift('0');
      return uid.join('');
    }
    
    /////////////////////////////////////////////
    // Set or clear the hashkey for an object. //
    ////////////////////////////////////////////
    
    function setHashKey(obj, h) {
      if (h) {
        obj.$$hashKey = h;
      }
      else {
        delete obj.$$hashKey;
      }
    }
    
    function extend(dest) {
      var h = dst.$$hashKey;
      forEach(arguments, function(obj){
        if (obj !== dest) {
          forEach(obj, function(value, key){
            dest[key] = value;
          });
        }
      });
      setHashKey(dest,h);
      return dset;
    }
    
    function int(str) {
      return parseInt(str, 10);
    }
    
    
    function inherit(parent, extra) {
      return extend(new (extend(function() {},
        { prototype:parent })
      )(), extra);
    }
    
    ///////////////////////////////
       // Heath'sHash(map) //
       // keys & values //
     //////////////////////////////
    
    function hashKey(obj) {
      var objType = typeof obj,
          key;
    
      if (objType == 'object' && obj !== null) {
        if (typeof (key = obj.$$hashKey) == 'function') {
          // must invoke on object to keep the right this
          key = obj.$$hashKey();
        } else if (key === undefined) {
          key = obj.$$hashKey = nextUid();
        }
      } else {
        key = obj;
      }
    
      return objType + ':' + key;
    }
    
    ////////////////////////////////////////////
     
    function HashMap(array){
      forEach(array, this.put, this);
    }
    
    HashMap.prototype = {
      put: function(key, value) {
        this[hashKey(key)] = value;
      },
      get: function(key) {
        return this[hashKey(key)];
      },
      remove: function(key) {
        var value = this[key = hashKey(key)];
        delete this[key];
        return value;
      }
    };
                

    public by sTiLL-iLL @ SniPitz-KND  4777  3  7  16

    kwik dirty arraySort....

    kwik example of a complex array sort
    // sort a complex array
    
    var mehAry = [{id: 140, name: "abc", age: "twenty"},
                  {id: 62009, name: "def", age: "thirty"},
                  {id: 3030, name: "ghi", age: "forty" },
                  {id: 455, name: "jkl", age: "fifty" }];
          
    function complexSort (itm1, itm2) {
        var a = itm1.id, b = itm2.id;
        return (a - b);
    }
    
    var sortedArray = mehAry.sort(complexSort);  
    
    //  sortedArray = [{id: 140, name: "abc", age: "twenty"},{id: 455, name: "jkl", age: "fifty" },
    //                 {id: 62009, name: "def", age: "thirty"},{id: 3030, name: "ghi", age: "forty" }];                        

    public by sTiLL-iLL @ SniPitz-KND  532551  3  8  21

    Ajax again?? Wrap it!! XHR Agent 4Ya

    XHR wrapper! object pooling and cueing!!! EveryOneZ dOing IT!
    
    var myXHR = {
           ESpec: function (wrap, evt) {
               return { xhrWrap: wrap, event: evt };
           },
           Agent: function(maxConnect) {
               var bCued = [], slf = this,
                   max = maxConnect || 3;
                   this.curCon = 0;
               function inCue() {
                   if (self.bCued < max) {
                       self.bCued++;
                       var itm = is.Readied.shift();
                       itm.evt.addEventListener(['EVENT_COMPLETE'], 
                         function (e) {
                             self.bCued--;
                             if (this.Readied.length !== 0) {
                               inCue();
                             }
                         });
                       itm.wrap.call(itm, args, itm.evt);
                    }
               }
               this.Readied = function (ESpec) {
                   bCued.push(ESpec);
                   inCue();
                   return ESpec.evt;
               };
            }
       };
    
                

    public by sTiLL-iLL @ SniPitz-KND  4716  12  8  28

    my skreenScooper in pure js. schweet YO!

    self executing module. skreen shots from DA BROWSAH!
    // javascript screenshot in your face!!!
    
    (function (wIn) {
    	function toAbso(urlz) {
    		if (!urlz.length) {
    		return [];
    	}
    
    	var attrNm = 'href', imgPrto = Object.create(HTMLImageElement.prototype),
    	    scptPrto = Object.create(HTMLScriptElement.prototype);
    	if (urlz[0].prototype === imgPrto || urlz[0].prototype === scptPrto) {
    		attrNm = 'src';
    	}
    
    	urlz = [].map.call(urlz, function (el, i) {
    	  var attr = el.getAttribute(attrNm);
    	  if (!attr) {
    		  return;
    	  }
    	  var dta = /^(https?|data):/i.test(attr);	
    	  if (dta) {
    		  return el;
    	  }
    	  else {
    		  return el;
    	  }});
    	  
    	return urlz;
    }
    
    function shootIt() {
    	toAbso(document.images);
    	toAbso(document.querySelectorAll("link[rel='stylesheet']"));
    	
      var sht = document.documentElement.cloneNode(true),
          shts = sht.style,
          shtd = sht.dataset,
          hed = sht.querySelector('head'),
          scpt = document.createElement('script');
          b = document.createElement('base');
          b.href = document.location.protocol + '//' + location.host;
          hed.insertBefore(b, hed.firstChild);
    
    	shtd.scrollX = wIn.scrollX;
    	shtd.scrollY = wIn.scrollY;
    	shts.pointerEvents, shts.userSelect, shts.webkitUserSelect,
    	shts.mozUserSelect, shts.msUserSelect, shts.oUserSelect = 'none';
    	shts.overflow = 'hidden';
    	scpt.textContent = '(' + onReadyGo.toString() + ')();';
    	sht.querySelector('body').appendChild(scpt);
    	
    	var blb = new Blob([sht.outerHTML], {
    		type: 'text/html'
    	});
    	return blb;
    }
    
    var seeIt = function() {
    	wIn.URL = wIn.URL || wIn.webkitURL;
    	wIn.open(wIn.URL.createObjectURL(shootIt()));
    };
    
    var onReadyGo = function() {
    	wIn.addEventListener('DOMContentLoaded', function (e) {
    		var xx = document.documentElement.dataset.scrollX || 0;
    		var yy = document.documentElement.dataset.scrollY || 0;
    		wIn.scrollTo(xx, yy);
    	});
    };
    
    wIn.seeIt = seeIt;
    
    })(window);            

    public by sTiLL-iLL @ SniPitz-KND  3601  4  8  25

    Enumerator.js... behind every enumeration you'll find a good Iterator. I guess.... LoL

    the future is now!
    // slick as snot Enumerable type!!!! yeah!
    
    var Enum = {
          create: function (collection) {
            var index=0;
            return {
              next: function() {
                if (index < collection.length) {
                  return ({ value: collection[index++], done: false });
                }
                else {
                  return ({ value: null, done: true});
                }
             }
          };
       }
    };
    
    // use it like this... (strings, bool, numbers, all gewd!)
    
    var arr=['rtJKvE', '!!@wrh', 433, 'yippe', 216,'PRdUrg', 3038, 'whaa?'],
      it = Enumerator.create(arr),
      primer = 0;
    
    while(primer !== null) {
      primer = it.next().value;
    	document.writeLine(primer);
    }
                
    • Public Snippets
    • Channels Snippets