Archived functions for posterity
Throughout this site I refer to my standard set of JavaScript functions. I think every developer has a set which they constantly reuse project to project. I thought I'd create a page outlining the ones I use. I hope you find them as useful as I do.
Each snippet is presented in long-hand easily readable form followed by a compressed single line version.
I strongly advise leaving in a credit to the original author along with a URL. You never know when you'll need the original article again, say for an update, and it's polite.
Damn those Crockford and Resig fellas, for making me code in a better manner. I've updated a few of the oldies and promoted them to the top. Older versions are now deprecated.
UK Postcode validation
author: john gardner 8th September 2011
This function checks the value of the parameter for a valid postcode format. The space between the inward part and the outward part is optional, although is inserted if not there as it is part of the official postcode.
If the postcode is found to be in a valid format, the function returns the postcode properly formatted (in capitals with the outward code and the inward code separated by a space. If the postcode is deemed to be incorrect a value of null is returned.
An example call for a form element with an id="postcode":
var postcode = checkPostCode(document.getElementById('postcode').value);
if (postcode) {
document.getElementById('postcode').value = postcode;
... do stuff ...
} else {
alert("Valid UK post code required");
}
Updated original version was run through JSLint prior to upload and compression.
// UK Postcode validation - John Gardner - http://www.braemoor.co.uk/software/postcodes.shtml
function checkPostCode(toCheck) {
var alpha1 = "[abcdefghijklmnoprstuwyz]",
alpha2 = "[abcdefghklmnopqrstuvwxy]",
alpha3 = "[abcdefghjkpmnrstuvwxy]",
alpha4 = "[abehmnprvwxy]",
alpha5 = "[abdefghjlnpqrstuwxyz]",
pcexp = [],
postCode = toCheck,
valid = false,
i;
pcexp.push(new RegExp("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$", "i"));
pcexp.push(new RegExp("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$", "i"));
pcexp.push(new RegExp("^(" + alpha1 + "{1}" + alpha2 + "{1}" + "?[0-9]{1}" + alpha4 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$", "i"));
pcexp.push(/^(GIR)(\s*)(0AA)$/i);
pcexp.push(/^(bfpo)(\s*)([0-9]{1,4})$/i);
pcexp.push(/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);
pcexp.push(/^([A-Z]{4})(\s*)(1ZZ)$/i);
pcexp.push(/^(ai-2640)$/i);
for (i = 0; i < pcexp.length; i++) {
if (pcexp[i].test(postCode)) {
pcexp[i].exec(postCode);
postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
postCode = postCode.replace(/C\/O\s*/, "c/o ");
if (toCheck.toUpperCase() === 'AI-2640') {
postCode = 'AI-2640';
}
valid = true;
break;
}
}
return valid ? postCode : null;
}
Short form:
// UK Postcode validation - John Gardner - http://www.braemoor.co.uk/software/postcodes.shtml
function checkPostCode(I){var A="[abcdefghijklmnoprstuwyz]",B="[abcdefghklmnopqrstuvwxy]",C="[abcdefghjkpmnrstuvwxy]",D="[abehmnprvwxy]",E="[abdefghjlnpqrstuwxyz]",G=[],H=I,J=false,F;G.push(new RegExp("^("+A+"{1}"+B+"?[0-9]{1,2})(\\s*)([0-9]{1}"+E+"{2})$","i"));G.push(new RegExp("^("+A+"{1}[0-9]{1}"+C+"{1})(\\s*)([0-9]{1}"+E+"{2})$","i"));G.push(new RegExp("^("+A+"{1}"+B+"{1}?[0-9]{1}"+D+"{1})(\\s*)([0-9]{1}"+E+"{2})$","i"));G.push(/^(GIR)(\s*)(0AA)$/i);G.push(/^(bfpo)(\s*)([0-9]{1,4})$/i);G.push(/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);G.push(/^([A-Z]{4})(\s*)(1ZZ)$/i);G.push(/^(ai-2640)$/i);for(F=0;F<G.length;F++){if(G[F].test(H)){G[F].exec(H);H=RegExp.$1.toUpperCase()+" "+RegExp.$3.toUpperCase();H=H.replace(/C\/O\s*/,"c/o ");if(I.toUpperCase()==="AI-2640"){H="AI-2640";}J=true;break;}}return J?H:null;}
For further details, including annotated code, please see the original article: Validating UK post codes. Which also includes PHP and VBScript versions too.
Get elements by class name: $elsByClassName()
author: mike foskett uploaded: 16th July 2010
Requires $id(), $els(), hasClass():
function $elsByClassName(id, element, classname) {
// returns a list of objects of element.classname or false.
// results are cached so function is useless for detecting changed classes, e.g. class="on".
var a = [], i, obj, pointer;
element = element || "*";
pointer = id + element + classname;
if ($elsByClassName.cache[pointer] === undefined) { // get a result the long way round
$elsByClassName.cache[pointer] = false; // cache negative result too
if ($id(id) && classname) {
obj = $els(id, element); // this result is cached separately
i = obj.length;
while (i--) {
if (hasClass(obj[i], classname)) {
a.push(obj[i]);
}
}
if (a.length) {
$elsByClassName.cache[pointer] = a.reverse(); // cache it for next time
}
}
}
return $elsByClassName.cache[pointer];
}
$elsByClassName.cache={}; // create global property
Short form:
function $elsByClassName(id,e,c){var a=[],i,o,p;e=e||"*";p=id+e+c;if($elsByClassName.cache[p]===undefined){$elsByClassName.cache[p]=false;if($id(id)&&c){o=$els(id,e);i=o.length;while(i--){if(hasClass(o[i],c)){a.push(o[i]);}}if(a.length){$elsByClassName.cache[p]=a.reverse();}}}return $elsByClassName.cache[p];}
$elsByClassName.cache={};
Controlling classes: hasClass(), removeClass(), addClass()
author: uploaded: 16th July 2011
Using regular expressions:
function hasClass(obj, c) {
return new RegExp('(\\s|^)' + class + '(\\s|$)').test(obj.className);
}
function addClass(obj, class) {
if (!hasClass(obj, class)) {
obj.className += ' ' + class;
}
}
function removeClass(obj, class) {
if (hasClass(obj, class)) {
obj.className = obj.className.replace(new RegExp('(\\s|^)' + class + '(\\s|$)'), ' ').replace(/\s+/g, ' ').replace(/^\s|\s$/, '');
}
}
Acts exactly as you'd wish, especially the removeClass() which removes leading and trailing spaces. It nicely removes a centered class too
Short form:
function hasClass(o,c){return new RegExp('(\\s|^)'+c+'(\\s|$)').test(o.className);}
function addClass(o,c){if(!hasClass(o,c)){o.className+=' '+c;}}
function removeClass(o,c){if(hasClass(o,c)){o.className=o.className.replace(new RegExp('(\\s|^)'+c+'(\\s|$)'),' ').replace(/\s+/g,' ').replace(/^\s|\s$/,'');}}
Shorten document.getElementById (version 2) - $id()
author: mike foskett uploaded: 4th October 2008
updated: 16th July 2011
Saves repeatedly writing out document.getElementById('idname')
:
function $id(id) {
if ($id.cache[id] === undefined) {
$id.cache[id] = document.getElementById(id) || false;
}
return $id.cache[id];
}
$id.cache = {};
Results are cached which speeds up repeat requests by 50%.
Short form:
function $id(i){return $id.cache[i]===undefined?$id.cache[i]=document.getElementById(i)||false:$id.cache[i];}
$id.cache={};
Get collection of elements (version 2) - $els()
Author: mike foskett uploaded: 5th April 2011
updated: 16th July 2011
Simplifies:
var obj = document.getElementbyId('idName');
if (obj) {
var divElements = obj.getElementsByTagName('div');
if (divElements.length > 0) {
for (var i = 0; i < divElements.length; i += 1) {
// do stuff with divElements[i] etc
}
}
}
Into:
var divElements = $els('idName', 'div');
var i = divElements.length;
while (i--) {
// do stuff with divElements[i] etc
}
Or:
if (els('idname','div')){
// do stuff with els('idname','div')[0] etc
}
Returns the list of elements if it's > 0, or a boolean false.
The beauty is the results from $els() are cached so repeat requests are 50% faster.
Function in full:
function $els(id, el) {
var a = id + el, obj;
if ($els.cache[a] === undefined) {
obj = document.getElementById(id);
if (obj) {
$els.cache[a] = obj.getElementsByTagName(el || "*") || false;
} else {
$els.cache[a] = false;
}
}
return $els.cache[a];
}
$els.cache = {};
Short form:
function $els(i,e){var a=i+e,o;if($els.cache[a]===undefined){o=document.getElementById(i);if(o){$els.cache[a]=o.getElementsByTagName(e||"*")||false;}else{$els.cache[a]=false;}}return $els.cache[a];}
$els.cache={};
Title case / capitalize text string
author: 17th December 2010
uploaded:Converts the first letter of each word in a string to a capital letter:
String.prototype.capitalize = function() {
return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){return p1+p2.toUpperCase();});
};
Usage:
textString.capitalize();
Note it does not convert the other letters to lowercase so in practice it may be better to:
textString.toLowerCase().capitalize();
Short form:
String.prototype.capitalize=function(){return this.replace(/(^|\s)([a-z])/g,function(m,p1,p2){return p1+p2.toUpperCase();});};
Full details see: Capitalize Words Using JavaScript
Simple is IE test
uploaded: 9th July 2010
A very simple IE boolean test found on the net:
var isIE = /*@cc_on!@*/false;
Returns true if you're using any version of IE, otherwise false.
Cross-browser mouseenter and mouseleave
author: 1st June 2010
uploaded:A cross browser script to emulate IE's mouseenter / mouseleave functions. these functions do not use event bubbling. The original article didn't supply a minified example:
// Cross-browser mouseenter and mouseleave, without event bubbling - http://blog.stchur.com/2007/03/15/mouseenter-and-mouseleave-events-for-firefox-and-other-non-ie-browsers/
var xb={eH:[],
uID:function(_e){if(_e===window){return 'theWindow';}else if(_e===document){return 'theDocument';}else {return _e.uniqueID;}},
addEvent:function(_e,_eN,_fn,_uC){if(typeof _e.addEventListener!='undefined'){if(_eN=='mouseenter'){_e.addEventListener('mouseover',xb.mouseEnter(_fn),_uC);}else if(_eN=='mouseleave'){_e.addEventListener('mouseout',xb.mouseEnter(_fn),_uC);}else{_e.addEventListener(_eN,_fn,_uC);}}else if(typeof _e.attachEvent!='undefined'){var key='{FNKEY::obj_'+xb.uID(_e)+'::evt_'+_eN+'::fn_'+_fn+'}',f=xb.eH[key];if(typeof f!='undefined'){return;}f=function(){_fn.call(_e);};xb.eH[key]=f;_e.attachEvent('on'+_eN,f);window.attachEvent('onunload',function(){_e.detachEvent('on'+_eN,f);});key=null;}else{_e['on' + _eN]=_fn;}},
removeEvent:function(_e,_eN,_fn,_uC){if(typeof _e.removeEventListener!='undefined'){_e.removeEventListener(_eN,_fn,_uC);}else if(typeof _e.detachEvent!='undefined'){var key='{FNKEY::obj_'+xb.uID(_e)+'::evt'+_eN+'::fn_'+_fn+'}';var f=xb.eH[key];if(typeof f!='undefined'){_e.detachEvent('on'+_eN,f);delete xb.eH[key];}key=null;}},
mouseEnter:function(_pFn){return function(_evt){var rT=_evt.relatedTarget;if(this==rT || xb.isAChildOf(this,rT)){return;}_pFn.call(this,_evt);};},
isAChildOf:function(_parent,_child){if(_parent==_child){return false;}while(_child && _child!=_parent){_child=_child.parentNode;}return _child==_parent;}
};
Useage:
xb.addEvent(obj, 'mouseenter', enter(e), false);
xb.addEvent(obj, 'mouseleave', leave(e), false);
function enter(e){
alert('mouseenter: ' + this.id);
}
function leave(e){
alert('mouseleave: ' + this.id);
}
Further details: Mouseenter and mouseleave events for Firefox (and other non-IE browsers).
Strip anchor from URL
author: mike foskett uploaded: 20th May 2010
Strips out just the anchor from a URL string:
function getAnchorFromURI(uri) {
return uri.slice(uri.lastIndexOf('#') + 1);
}
Short form:
function getAnchorFromURI(u){return u.slice(u.lastIndexOf('#')+1);}
Regex form validation functions
uploaded: 18th May 2010
Form validation functions using regex. Each returns a boolean either true or false.
function isInteger(str) { // positive or negative integer without range check.
return (/^-?\d+$/.test(str));
}
function isPositiveDecimal(str) { // positive only, integer or decimal point.
return (!/\D/.test(str)) || (/^\d+\.\d+$/.test(str));
}
function isAlphanumeric(str) { // [a-z],[A-Z],[0-9] only
return !(/\W/.test(str));
}
function isAlphanumericSpaceAmpersandHyphen(str) { // [a-z],[A-Z],[0-9], ,&,-] only
return !(/^[\w &\-]+$/.test(str));
}
function validEmail(str) {
return str.match(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/) === null;
}
Please inspect the test cases prior to using these functions:
Function | Test cases | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
abc | & | - | ab1 | 12a | 123 | -123 | 1.23 | -1.2 | "" | " " | NULL | |
isInteger | False | False | False | False | False | True | True | False | False | False | False | False |
isPositiveDecimal | False | False | False | False | False | True | False | True | False | True | False | False |
isAlphanumeric | True | False | False | True | True | True | False | False | False | True | False | True |
isAlphanumeric Plus: " ","&", "-" |
True | True | True | True | True | True | True | False | False | False | True | True |
Note: Pay particular attention to the empty string and null results.
Short form:
function isInteger(s){return (/^-?\d+$/.test(s));}
function isPositiveDecimal(s){return (!/\D/.test(str))||(/^\d+\.\d+$/.test(s));}
function isAlphanumeric(str){return !(/\W/.test(s));}
function isAlphanumericSpaceAmpersandHyphen(s){return !(/^[\w &\-]+$/.test(s));}
function validEmail(s){return s.match(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/)===null;}
Cross-browser setting the style attribute
author: 25th March 2010
uploaded:IE doesn't play well with setAttribute. Here's a simple cross-browser method for setting a style attribute on an object:
function setStyle(obj, styleStr) {
obj.setAttribute('style', styleStr);
obj.style.cssText = styleStr;
}
Short form:
function setStyle(o,s){o.setAttribute('style',s);o.style.cssText=s;}
Though ideally the methods should be tested for before usage.
Further details: setAttribute does not work when used with the style attribute.
Switching input auto-complete off
author: mike foskett uploaded: 20th February 2010
Auto complete is a proprietary Microsoft attribute, and deemed invalid in XHTML, but widely supported by most browsers. Very useful for private fields on public machines.
document.getElementById('inputID').setAttribute("autocomplete", "off");
Note the method described requires JavaScript to be of any use.
Cross browser viewport width & height
author: mike foskett uploaded: 4th February 2010
Requires isLessThanIE() function
Short form:
var w=isLessThanIE(8)?(!(document.documentElement.clientWidth)||(document.documentElement.clientWidth===0))?document.body.clientWidth:document.documentElement.clientWidth:window.innerWidth;
var h=isLessThanIE(8)?(!(document.documentElement.clientHeight)||(document.documentElement.clientHeight===0))?document.body.clientHeight:document.documentElement.clientHeight:window.innerHeight;
Based on: Find viewport height / width, crossbrowser.
Cross browser whole document width & height
author: 2nd November 2006
uploaded:Gets the width and height of the whole document including the area offscreen.
Short form:
var docH=(document.height!==undefined)?document.height:document.body.offsetHeight;
var docW=(document.width!==undefined)?document.width:document.body.offsetWidth;
Further details: Javascript Get Page Height With Scroll.
I recently had issue with Firefox and the height calculation. Consequently I found a new function to generate page height:
author: 7th January 2011
uploaded:
function getDocHeight(){var D=document;return Math.max(Math.max(D.body.scrollHeight,D.documentElement.scrollHeight),Math.max(D.body.offsetHeight,D.documentElement.offsetHeight),Math.max(D.body.clientHeight,D.documentElement.clientHeight));}
Original article: Get document height (cross-browser).
Using wrap on an XHTML textarea
author: bob ince uploaded: 28th January 2010
Wrap is a deprecated attribute in XHTML but occasionally you still need to switch it:
function setWrap(area, wrap) {
if (area.wrap) {
area.wrap = wrap;
} else { // wrap attribute not supported - try Mozilla workaround
area.setAttribute('wrap', wrap);
var newarea = area.cloneNode(true);
newarea.value = area.value;
area.parentNode.replaceChild(newarea, area);
}
}
Pass in the textarea object and wrap state
Short form:
function setWrap(a,w){if(a.w){a.w=w;}else{a.setAttribute('wrap',w);var n=a.cloneNode(true);n.value=a.value;a.parentNode.replaceChild(n,a);}}
Example: Switch wrap off on a textarea with id="ta"
setWrap(document.getElementById('ta'), "off");
It is best to back this with a little CSS too:
textarea {white-space:pre; overflow:auto}
Further details: Changing textarea wrapping using javascript.
IE version test - isLessThanIE(version)
author: mike foskett 21st January 2010
Not a recommended method but, on rare occasion, incredibly useful.
function isLessThanIE(version) {
if (navigator.appName === 'Microsoft Internet Explorer') {
var ua = navigator.userAgent,
re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) !== null) {
if (parseFloat(RegExp.$1) < version) {
return true;
}
}
}
return false;
}
Short form version:
function isLessThanIE(v){if(navigator.appName=='Microsoft Internet Explorer'){var u=navigator.userAgent,r=new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");if(r.exec(u)!==null){if(parseFloat(RegExp.$1)<v){return true;}}}return false;}
Integer validation - isInteger(str)
author: mike foskett 21st January 2010
Tests a string contains only numeric characters (0 - 9) using a regular expression. The string may start with a minus (-). The integer value is not range checked. Primarily used for form input validation.
function isInteger(str) {
return (/^-?\d+$/.test(str));
}
Short form version:
function isInteger(s){return(/^-?\d+$/.test(s));}
Alternate, positive only, version:
function isPositiveInteger(s){return(/^\d+$/.test(s));}
Faster for-next looping
author: mike foskett 23rd October 2009
Only use if you're trawling through many objects in the DOM, use a fast for-next loop. Replace:
var allDivs=document.getElementsByTagName('div');
for (var i=0; i<allDivs.length; i++){
// do stuff with every div
}
With:
var allDivs = document.getElementsByTagName('div');
for (var i = allDivs.length-1; i > -1; i--) {
// do stuff with every div
}
The method is faster because there are less calculations on each iteration. The loop works backwards though. That is it starts from the top limit (allDivs.length-1) down to 0.
Optionally you could use a while loop, which may be quicker:
var allDivs = document.getElementsByTagName('div'),
i = allDivs.length;
while (i--) {
// do stuff with every div
}
Accessible pop-up window link using an inline script
author: mike foskett 13th October 2009
updated: 24th March 2010
Not an advised technique but sometimes very useful.
<p>
<a onclick="var w=620,h=350,newWindow=window.open(this.href,'newWin','resizable,toolbar=0,location=0,scrollbars=1,menubar=0,width='+w+',height='+h+',top='+(screen.height-h)/2+',left='+(screen.width-w)/2+'');newWindow.focus();return false;" href="tandc.html" title="Open's in a new window">Terms and conditions</a>
</p>
This version:
- Gets content from href address.
- Allows a fixed width and height.
- Places the window screen centre.
- Adds focus to the window so it always comes to the front.
- Content available without JavaScript.
Last update repaired screen centring issue.
Simple closure space example
author: mike foskett 13th October 2009
A simple closure used to encapsulate JavaScript functions. Useful and advisable if you work on large sites with complex JavaScript includes as it helps prevent unwanted interactions.
var closureSpace=function(){
function init() {
...
}
return{ // list externally available functions here
init:init
};
}();
closureSpace.init(); // call externally available function like this
Is CSS available? hasCSS()
author: mike foskett 13th October 2009
A small function to test that CSS is on and available. Used to prevent Javascript functions acting on styles when their already off, unavailable, or not supported.
It works by adding a hidden div to the end of the document and testing its display property.
The function returns a boolean. I found it best to set a global variable to that result for use.
var cssOn; // Global variable
function hasCSS() {
var d, o, v = false;
// add a new div to the end of the body.
d = document.createElement('div');
d.id = "hasCSS";
document.body.appendChild(d);
// test new div display property (set in css).
o = document.getElementById("hasCSS");
if (window.getComputedStyle) {
v = (window.getComputedStyle(o, null).getPropertyValue('display') === 'none');
} else {
if (o.currentStyle) {
v = (o.currentStyle.display === 'none');
}
}
// remove div.
document.body.removeChild(d);
// return test result.
return v;
}
// run first on page load using addLoadEvent found elsewhere on this page.
addLoadEvent(function() {cssOn = hasCSS();});
The Short form version:
function hasCSS(){var d=document.createElement('div');d.id="hasCSS";document.body.appendChild(d);var o=document.getElementById("hasCSS"),v=false;if(window.getComputedStyle){v=(window.getComputedStyle(o,null).getPropertyValue('display')==='none');}else{if(o.currentStyle){v=(o.currentStyle.display==='none');}}document.body.removeChild(d);return v;}
// run once on page load (use addLoadEvent or similar function)
var cssOn=hasCSS();
Somewhere in the style sheet this is required:
#hasCSS {display:none}
To use the function:
if (cssOn) {
...
}
Cross-browser getNextSibling()
author: mike foskett 8th January 2009
Firefox and IE see things differently when accessing the nextSibling. This function balances those differences to provide a simple cross-browser solution:
function getNextSibling(obj) {
var next = obj.nextSibling;
while (next.nodeType !== 1) {
next = next.nextSibling;
}
return next;
}
The Short form version:
function getNextSibling(o){var n=o.nextSibling;while(n.nodeType!=1){n=n.nextSibling;}return n;}
An example of usage. Show a hidden div which is the next sibling to a links parent:
.show {display:block}
.hide {display:none}
<h3>
<a href="#" onclick="getNextSibling(this.parentNode).className='show'; return false">Show div content</a>
</h3>
<div class="hide">
...
</div>
Launch a new window in XHTML strict
author: mike foskett uploaded: 10th October 2008
updated: 13th September 2010
After dealing with pages which contained hundreds of links I thought it judicial to update the function to use the fastest loop method. The code has also been verified by JSLint. 28th March 2009
Add rel="external"
to each external link:
<a href="someAddress.html" rel="external">external link to some page</a>
Then JavaScript unobtrusively adds a target to each link marked by rel="external"
. A title is also added to each link informing the user that it opens in a new window:
// Links with rel="external" get launched into new window
function externalLinks() {
var links, i, A;
links = document.getElementsByTagName("a");
i = links.length;
while (i--) {
A = links[i];
if (A.getAttribute("href") && A.getAttribute("rel") === "external") {
A.target = "_blank";
A.title = (A.title !== "") ? A.title + " (launches in a new window)" : "Launches in a new window";
}
}
}
Short form:
// Links with rel="external" get launched into new window
function externalLinks(){var L,i,A;L=document.getElementsByTagName("a");i=L.length;while(i--){A=L[i];if(A.getAttribute("href")&&A.getAttribute("rel")==="external"){A.target="_blank";A.title=(A.title!=="")?A.title+" (launches in a new window)":"Launches in a new window";}}}
Latest update removed: A.onclick=function(){return false;};
which overwrote the href action - Doh!
Executing JavaScript on page load - addLoadEvent()
author: simon willisons 26th May 2004
A beautiful onload handler which allows multiple functions to be run once the page has loaded:
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload !== 'function') {
window.onload = func;
} else {
window.onload = function () {
if (oldonload) {
oldonload();
}
func();
};
}
}
addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
addLoadEvent(function () {
// more code to run on page load
});
Here's the short form version:
// author: Simon Willisons - http://simonwillison.net/2004/May/26/addLoadEvent/
function addLoadEvent(f){var o=window.onload;if(typeof window.onload!=='function'){window.onload=f;}else{window.onload=function(){if(o){o();}f();};}}
Further details: Executing JavaScript on page load.
Separation of CSS and JavaScript - jsCSS()
author: christian heilmann uploaded: 4th October 2008
Avoid using JavaScript for presentational effects. Use this function to swap, add, remove, check or toggle a class name.
Original modified to include a class toggle switch:
// className: swap, add, remove, check or toggle - author: Christian Heilmann - http://www.onlinetools.org/articles/unobtrusivejavascript/cssjsseparation.html
function jsCSS(action, obj, class1, class2) {
var rep;
switch (action) {
case 'swap':
obj.className = !jsCSS('check', obj, class1) ? obj.className.replace(class2, class1) : obj.className.replace(class1, class2);
break;
case 'add':
if (!jsCSS('check', obj, class1)) {obj.className += obj.className ? ' ' + class1 : class1; }
break;
case 'remove':
rep = obj.className.match(' ' + class1) ? ' ' + class1 : class1;
obj.className = obj.className.replace(rep, '');
break;
case 'check':
return new RegExp('\\b' + class1 + '\\b').test(obj.className);
case 'toggle':
if (jsCSS('check', obj, class1)) {
jsCSS('remove', obj, class1);
} else {
jsCSS('add', obj, class1);
}
break;
}
}
Short form:
// jsCSS(action,object,class1,class2) - className: swap, add, remove, check or toggle - author: Christian Heilmann - http://www.onlinetools.org/articles/unobtrusivejavascript/cssjsseparation.html
function jsCSS(a,o,c1,c2){switch(a){case'swap':o.className=!jsCSS('check',o,c1)?o.className.replace(c2,c1):o.className.replace(c1,c2);break;case'add':if(!jsCSS('check',o,c1)){o.className+=o.className?' '+c1:c1;}break;case'remove':var rep=o.className.match(' '+c1)?' '+c1:c1;o.className=o.className.replace(rep,'');break;case'check':return new RegExp('\\b'+c1+'\\b').test(o.className);case'toggle':if(jsCSS('check',o,c1)){jsCSS('remove',o,c1);}else{jsCSS('add',o,c1);}break;}return false;}
Further details: Separation of CSS and JavaScript.
Check an id exists - idExists()
author: mike foskett uploaded: 4th October 2008
Check an id actually exists prior to using it:
function $idExists(id) {
return (document.getElementById(id) !== null);
}
Short form requires the $id() function too:
function $idExists(i){return(document.getElementById(i)!==null);}
Affecting styles before JavaScript is loaded - .hasJS
author: mike foskett uploaded: 4th October 2008
Add this snippet directly after the page title and it adds a class of .hasJS to the html element if JavaScript is present. It allows the style sheet to style components used by JavaScript before the page fully loads:
<script>/*<![CDATA[*/document.documentElement.className="hasJS";/*]]>*/</script>
Which means the style sheet can act on any styles affected by the JavaScript prior to loading the JavaScript. For instance; consider hiding a block only when JavaScript is available:
.hasJS .hide {display:none}
Check DOM functions are supported - isDom()
author: mike foskett uploaded: 4th October 2008
It's always best to test that the DOM functions you wish to use are supported prior to using them. Extend or abbreviate as required:
function isDom() {
return (
document.getElementById
&& document.getElementsByTagName
&& document.createElement
) ? true : false;
}
Short form:
function isDom(){return (document.getElementById&&document.getElementsByTagName&&document.createElement)?true:false}
This function should be called first, before any other scripting. All JavaScript should degrade gracefully and, personally, if the functions I use are not supported then I do not deliver any script at all. For example:
if (isDom()){
addLoadEvent(setup);
}
Setting opacity cross-browser - setOpacity()
author: mike foskett uploaded: 4th October 2008
updated: 5th April 2011
Setting the opacity level of an object is not yet a standard. The following snippet irons out cross-browser inconsistencies:
This update tests the object exists prior to setting it's opacity.
Original id based version:
function setOpacity(id, opacity) {
var object = document.getElementById(id).style;
if (object) {
object.filter = "alpha(opacity=" + opacity + ")";
object.opacity = opacity / 100;
object.MozOpacity = opacity / 100;
object.KhtmlOpacity = opacity / 100;
}
}
Short form requires $id():
function setOpacity(id,op){var o=$id(id).style;if(o){o.opacity=op/100;o.MozOpacity=op/100;o.KhtmlOpacity=op/100;o.filter="alpha(opacity="+op+")";}}
The function may be called via a timed loop for fading purposes. This example fades in an object with an id of idname:
for (var i = 0; i < 101; i += 25) {
setTimeout("setOpacity('idname', " + i + ")", i*2);
}
Updated object based version:
author: mike foskett uploaded: 21st January 2010
This version has no prerequisites and includes method checking.
function setOpacity(obj, xOpacity) {
if (typeof obj.style.MozOpacity !== "undefined") {
obj.style.MozOpacity = xOpacity;
} else {
if (typeof obj.style.opacity !== "undefined") {
obj.style.opacity = xOpacity;
} else {
if (typeof obj.style.filter !== "undefined") {
obj.style.filter = "alpha(opacity=" + xOpacity * 100 + ")";
}
}
}
}
Short form:
function setOpacity(o,op){if(typeof o.style.MozOpacity!=="undefined"){o.style.MozOpacity=op;}else{if(typeof o.style.opacity!=="undefined"){o.style.opacity=op;}else{if(typeof o.style.filter!=="undefined"){o.style.filter="alpha(opacity="+op*100+")";}}}}
Convert CSS property to camel case - hyphenToCamel()
author: steffen rusitschka uploaded: 4th October 2008
:
function hyphenToCamel(s) {
var exp;
for (exp = /-([a-z])/; exp.test(s); s = s.replace(exp, RegExp.$1.toUpperCase())) {}
return s;
}
function hyphenToCamel(s){var E;for(E=/-([a-z])/;E.test(s);s=s.replace(E,RegExp.$1.toUpperCase())){}return s;}
Short form version is pretty much the same:
// author: Steffen Rusitschka - http://www.ruzee.com/blog/2006/07/retrieving-css-styles-via-javascript/
function hyphenToCamel(s){var E;for(E=/-([a-z])/;E.test(s);s=s.replace(E,RegExp.$1.toUpperCase())){}return s;}
Further details: Retrieving CSS styles via JavaScript.
Retrieving CSS properties with JavaScript - getStyleProperty()
author: mike foskett uploaded: 4th October 2008
Cross-browser method to obtain a CSS property
Please note this function is not 100% for retrieving all CSS properties but does work on most of them. Function requires hyphenToCamel():
function getStyleProperty(id, property) {
// note this function is not 100% generic for all CSS properties
var obj = document.getElementById(id),
value = '';
if (window.getComputedStyle) {
value = window.getComputedStyle(obj, null).getPropertyValue(property);
} else {
if (obj.currentStyle) {
value = obj.currentStyle[hyphenToCamel(property)];
}
}
return value;
}
Short form requires both hyphenToCamel() and $id():
function getStyleProperty(i,P){var o=document.getElementById(i),V='';if(window.getComputedStyle){V=window.getComputedStyle(o,null).getPropertyValue(P);}else{if(o.currentStyle){V=o.currentStyle[hyphenToCamel(P)];}}return V;}
Further details: Retrieving CSS styles via JavaScript.
Test for Flash - isFlash()
author: mike foskett uploaded: 4th October 2008
updated: 20th May 2009
The function simply tests what version of Flash is available to the clients browser. Call the function with the minimum Flash version required eg: isFlash(7) and it returns false if unsupported or the supported Flash version eg 9:
Unfortunately I've lost the original reference for this script.
function isFlash(v){
var testTo=20, installed=0, x;
if(navigator.plugins && navigator.plugins.length){
for(x=0;x<navigator.plugins.length;x++){
if(navigator.plugins[x].name.indexOf('Shockwave Flash')!=-1){
installed=parseInt(navigator.plugins[x].description.split('Shockwave Flash ')[1],10);
break;
} } }
else if(window.ActiveXObject){
for(x=2;x<=testTo;x++){
try{if(eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash."+x+"');")){installed=x;}}
catch(e){}
} }
return((installed>=v)?installed:0);
}
Short form:
function isFlash(v){var t=20,i=0,c;if(navigator.plugins&&navigator.plugins.length){for(c=0;c<navigator.plugins.length;c++){if(navigator.plugins[c].name.indexOf('Shockwave Flash')!=-1){i=parseInt(navigator.plugins[c].description.split('Shockwave Flash ')[1],10);break;}}}else if(window.ActiveXObject){for(c=2;c<=t;c++){try{if(eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash."+c+"');")){i=c;}}catch(e){}}}return((i>=v)?i:0);}
Quickly replace content - replaceContent()
author: mike foskett uploaded: 4th October 2008
Replaces the content of an object referenced by it's id. Okay it uses innerHTML but tests have shown that it's fully supported by all browsers and executes quicker than DOM compliant methods:
function replaceContent(id, content) {
if (idExists(id)) {
document.getElementById(id).innerHTML = content;
}
}
Short form requires $id():
function replaceContent(id,c){if(idExists(id)){$id(id).innerHTML=c;}}
Cookie handling
author: peter-paul koch - uploaded: 4th October 2008
Create, and read from, cookies:
function makeCookie(name, value, days) {
var expires = "", date;
if (days) {
date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=",
ca = document.cookie.split(';'),
i,
c;
i = ca.length;
while (i--) {
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 killCookie(name) {
makeCookie(name, '', -1);
}
Short form:
// Cookie functions - Peter-Paul Koch: http://www.quirksmode.org/js/cookies.html
function makeCookie(N,V,D){var E="",A;if(D){A=new Date();A.setTime(A.getTime()+(D*24*60*60*1000));E="; expires="+A.toGMTString();}document.cookie=N+"="+V+E+"; path=/";}
function readCookie(N){var E=N+"=",C=document.cookie.split(';'),i,c;i=C.length;while(i--){c=C[i];while(c.charAt(0)===' '){c=c.substring(1,c.length);}if(c.indexOf(E)===0){return c.substring(E.length, c.length);}}return null;}
function killCookie(N){makeCookie(N,'',-1);}
Further details: Cookies.
Replace content via Ajax
author: jim ley - January 2006
I cannot honestly say I understand Jim's code here but it works very well:
// XMLHttpRequest methods - author Jim Ley - http://jibbering.com/2002/4/httprequest.html
var xmlhttp=false;
/*@cc_on @*/
/*@if (@_jscript_version>=5)
try{xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")}
catch(e){
try{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")}
catch(E){xmlhttp=false}
}
@else
xmlhttp=false;
@end @*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined'){
try{xmlhttp=new XMLHttpRequest()}
catch(e){xmlhttp=false}
}
if (!xmlhttp && window.createRequest){
try{xmlhttp=window.createRequest()}
catch(e){xmlhttp=false}
}
I use a replace function to work with Jim's script. It expects the fetched file to be valid XHTML for direct insertion.
function replaceAjaxContent(id,file)
if (xmlhttp){
xmlhttp.open("GET", file, true)
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4)
document.getElementById(id).innerHTML=xmlhttp.responseText
}
xmlhttp.send(null)
}
Short form requires replaceContent():
// XMLHttpRequest methods - author Jim Ley - http://jibbering.com/2002/4/httprequest.html
var xmlhttp=false;
/*@cc_on @*/
/*@if (@_jscript_version>=5)
try{xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")}catch(e){try{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")}catch(E){xmlhttp=false}}
@else
xmlhttp=false
@end @*/
if (!xmlhttp&&typeof XMLHttpRequest!='undefined'){try{xmlhttp=new XMLHttpRequest()}catch(e){xmlhttp=false}}
if (!xmlhttp&&window.createRequest){try{xmlhttp=window.createRequest()}catch(e){xmlhttp=false}}
function replaceAjaxContent(id,f)if(xmlhttp){xmlhttp.open("GET",f,true);xmlhttp.onreadystatechange=function(){if(xmlhttp.readyState==4){replaceContent(id,xmlhttp.responseText)}}xmlhttp.send(null)}}
Further details: Using the XML HTTP Request object.
As stated these are my personal tools of the trade, if you have any useful snippets please email or post them for consideration.
Social links and email client: