Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

« Newer Snippets
Older Snippets »
Showing 41-60 of 96 total

Disable a checkbox

Disable a checkbox via HTML or javascript.

<INPUT TYPE="checkbox" NAME="MyCheckbox" VALUE="Select Me" DISABLED>

document.forms[0].MyCheckbox.disabled = true;

Check / Uncheck all checkboxes in a pseudo group

This bit of javascript will check and uncheck all checkboxes in a group of checkboxes. The checkboxes are grouped by naming all the checkboxes by the same name.

Javascript Code:
function checkUncheckAll(checkAllState, cbGroup)
{
        // Check that the group has more than one element
        if(cbGroup.length > 0)
        {
                // Loop through the array
                for (i = 0; i < cbGroup.length; i++)
                {
                        cbGroup[i].checked = checkAllState.checked;
                }
        }
        else
        {
                // Single element so not an array
                cbGroup.checked = checkAllState.checked;
        }
}


HTML Code:
<input type=checkbox name=checkall onclick="checkUncheckAll(this, grp1);">
<input type=checkbox name=grp1 id=bx1>
<input type=checkbox name=grp1 id=bx2>
<input type=checkbox name=grp1 id=bx3>
<input type=checkbox name=grp1 id=bx4>

Load external file into div

// javascript to go into head of document or external .js file

function ahah(url, target) {
  document.getElementById(target).innerHTML = ' Fetching data...';
  if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    req = new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (req != undefined) {
    req.onreadystatechange = function() {ahahDone(url, target);};
    req.open("GET", url, true);
    req.send("");
  }
}  

function ahahDone(url, target) {
  if (req.readyState == 4) { // only if req is "loaded"
    if (req.status == 200) { // only if "OK"
      document.getElementById(target).innerHTML = req.responseText;
    } else {
      document.getElementById(target).innerHTML=" AHAH Error:\n"+ req.status + "\n" +req.statusText;
    }
  }
}

function load(name, div) {
        ahah(name,div);
        return false;
}


// call code with the name of the external file and the id of the div you want to put the content into

<a href="file1.html" onclick="load('file1.html','content');return false;">File 1a>

Generic Fast $(), getEl()

// Generic Fast $(), getEl() R.E.M
// e= id, element, array of..
// returns element or [] of elements

function getEl(e) {  
  if (typeof e == 'string') 
    {return window.document.getElementById(e);}  
  if (e[0]) {//array
    var i=e.length;     
    while(i--) {e[i]=arguments.callee(e[i]);}
    return e;}  return e;//element
}

Ajax Responders (Indicators)

// code for indicator registration

registers: {
        onCreate: function() {
                if(Ajax.activeRequestCount>0)
                        new Effect.Appear('indicate');
        },
        onComplete: function() {
                if(Ajax.activeRequestCount==0)
                        new Effect.Fade('indicate', {queue: 'end'});
        }
}

Ajax.Responders.register(Note.registers);

Loader

// use Loader.addOnLoad(function) to add onload events

var Loader = {
  loaded: false,
  addOnLoad: function(fn) {
    if (this.loaded) fn();
    else {
      var oldonload = (window.onload) ? window.onload : function () {};
      window.onload = function () { oldonload(); fn(); };
    }
  },
  init: function() {
    this.loaded = true;
  }
};
Loader.addOnLoad(Loader.init);

Update Title

// simple function to update a page's title

updateTitle: function(title) { document.title = title; }

Browser Dimensions

// various functions related to viewable browser dimensions and scroll offset

putCenter: function(item) {
  item = $(item);
  var xy = item.getDimensions();
  var win = this.windowDimensions();
  var scrol = this.scrollOffset();
  item.style.left = (win[0] / 2) + scrol[0] - (xy.width / 2) + "px";
  item.style.top = (win[1] / 2) + scrol[1] - (xy.height / 2) + "px";
},
fullScreen: function(item) {
  item = $(item);
  var win = this.windowDimensions();
  var scrol = this.scrollOffset();
  item.style.height = scrol[1] + win[1] + "px";
},
windowDimensions: function() {
  var x, y;
  if (self.innerHeight) {
    // all except Explorer
    x = self.innerWidth;
    y = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) {
    // Explorer 6 Strict Mode
    x = document.documentElement.clientWidth;
    y = document.documentElement.clientHeight;
  } else if (document.body) {
    // other Explorers
    x = document.body.clientWidth;
    y = document.body.clientHeight;
  }
  if (!x) x = 0;
  if (!y) y = 0;
  arrayWindowSize = new Array(x,y);
  return arrayWindowSize;
},
scrollOffset: function() {
  var x, y;
  if (self.pageYOffset) {
    // all except Explorer
    x = self.pageXOffset;
    y = self.pageYOffset;
  } else if (document.documentElement && document.documentElement.scrollTop) {
    // Explorer 6 Strict
    x = document.documentElement.scrollLeft;
    y = document.documentElement.scrollTop;
  } else if (document.body) {
    // all other Explorers
    x = document.body.scrollLeft;
    y = document.body.scrollTop;
  }
  if (!x) x = 0;
  if (!y) y = 0;
  arrayScrollOffset = new Array(x,y);
  return arrayScrollOffset;
}

Execute Event

// executes an event using the DOM element and event name (take out the throw $break to execute all of them)

execEvent: function(el, type) {
  Event.observers.each(function(item,index) {
    if (item[0] == el && item[1] == type) { item[2](); throw $break; }
  });
}

Get HTML

// a stupid function that gets a node's HTML, including the node itself

getHTML: function(node) {
  var div = document.createElement('DIV');
  div.appendChild(node.cloneNode(true));
  return div.innerHTML;
}

Insert Into Array

// insert item into array by specifying the array, insertion index - 1, and the item

insertArray: function(array, afterIndex, item) {
  var first = array.slice(0, afterIndex + 1);
  var second = array.slice(afterIndex + 1);
  first.push(item);
  return first.concat(second);
}

Get CSS Rule w/ Selector

// gets the rule for a specific CSS selector

getRule: function(selector) {
  var mysheet = document.styleSheets[0];
  var myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;
  for (i = 0; i < myrules.length; i++)
    if (myrules[i].selectorText.toLowerCase() == selector)
      return myrules[i];
  return;
}

childOfID

// moves upward in the tree until an ID or class name is found, returns element

childOfID: function(element, id, isClass) {
  element = $(element);
  do {
    if (isClass && element.hasClassName(id)) return element; 
    if (!isClass && element.id == id) return element;
  } while (element = $(element.parentNode));
  return false;
}

Catch Enter, Catch Escape

// used to catch form keydowns

catchEnter: function(e) {
  if (e.keyCode == 13) { Event.stop(e); return true; }
  else return false;
},
catchEsc: function(e) {
  if (e.keyCode == 27) { Event.stop(e); return true; }
  else return false;
}

Attach Events

// takes this.events with format 'element:event': function(e) { } and attaches it

attachEvent: function(selector) {
  var sel = selector.split(':');
  var el =  this.el[sel[0]];
  var ev =  sel[1];
  if (!el)      return;
  if (!el.each) Event.observe(el, ev, this.events[selector]);
  else el.each( function(item, index) {
    Event.observe(item, ev, this.events[selector]);
  }.bind(this));
},
attachEvents: function() {
  for (property in this.events) this.attachEvent(property);
},
removeEvent: function(selector) {
  var sel = selector.split(':');
  var el = this.el[sel[0]];
  var ev = sel[1];
  if (!el) return;
  if (!el.each) Event.stopObserving(el, ev, this.events[selector]);
  else el.each(function(item, index) {
    Event.stopObserving(item, ev, this.events[selector]);
  }.bind(this));
},
removeEvents: function() {
  for (x in this.events) this.removeEvent(x);
}

Attach Elements

// takes this.el and copies it to this.elements, replacing CSS selector with DOM object(s)

attachElement: function(p) {
  this.el[p] = $$(this.elements[p]);
  if (this.el[p].length == 1) this.el[p] = this.el[p][0];
},
attachElements: function() {
  this.el = {};
  for (x in this.elements) this.attachElement(x);
},
clearElements: function() {
  for (x in this.el) this.el[x] = null;
}

Bind Functions

// these functions force a common 'this' on inner objects

bindTo: function(source, bindTo) {
  if (typeof source == 'function') return;
  for (x in source)
    if (typeof source[x] == 'function')
      source[x] = source[x].bind(bindTo);
},
bindAll: function() {
  this.bindTo(this.events,   this);
  this.bindTo(this.ajax,     this);
  this.bindTo(this.complete, this);
}

Custom Ajax.Request Function

// this is a custom function that simplifies creating an ajax object

function(url, complete, form, params) {
  params = params ? $H(params).toQueryString() : '';
  if (!complete) complete = function(r){};
  if (form)      params   = Form.serialize(form) + '&' + params;
  new Ajax.Request(url, 
    { asynchronous:true,
      evalScripts:true, 
      onComplete: function(r) { complete(r.responseText); },
      parameters:params
    });
}

appendInputTypeClasses() - IE attribute selectors for form inputs

(Stolen from Jeremy Keith and Dustin Diaz: http://domscripting.com/blog/display/38).

Unobtrusive script takes a form inputs type attribute and copies it to that input's class. So, you go from...

<input type="text" />


...to...

<input type="text" class="text" />


Basically allows attribute selectors for form until IE catches up.

/*
        form.js
        AUTH: Austin Govella ([email protected])
        DATE: 2006-07-01
        DESC: Includes form specific javascripts.
        NOTE: Stolen from Jeremy Keith and Dustin Diaz: http://domscripting.com/blog/display/38
        REVS:  
*/



function appendInputTypeClasses()
{       /* adds input type as the inputs class */
        if ( !document.getElementsByTagName ) return;

        var inputs = document.getElementsByTagName('input');
        var inputLen = inputs.length;
        for ( i=0; i < inputLen; i++ )
        {
                if ( inputs[i].getAttribute('type') )
                {
                        inputs[i].className += ' '+inputs[i].getAttribute('type');
                }
        }
}

toHex()

// covert a color to hex

function toHex(dec) {
        // create list of hex characters
        var hexCharacters = "0123456789ABCDEF"
        // if number is out of range return limit
        if (dec < 0)
                return "00"
        if (dec > 255)
                return "FF"
        // decimal equivalent of first hex character in converted number
        var i = Math.floor(dec / 16)
        // decimal equivalent of second hex character in converted number
        var j = dec % 16
        // return hexadecimal equivalent
        return hexCharacters.charAt(i) + hexCharacters.charAt(j)
}
« Newer Snippets
Older Snippets »
Showing 41-60 of 96 total