Really useful JavaScript functions
author: mike foskett incept: 4th October 2008
last update: 20th February 2010
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.
Switching input auto-complete off
author: mike foskett uploaded: 20th February 2010
Auto complete is a propriatry 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");
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: uploaded: 2nd November 2006
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.
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
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.width-w)/2+',left='+(screen.height-h)/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.
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(){
// add a new div to the end of the body.
var d=document.createElement('div');
d.id="hasCSS";
document.body.appendChild(d);
// test new div display property (set in css).
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');
}
}
// 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 useage. 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>
UK Postcode validation
author: john gardner 8th August 2005
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 false 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");
}
// UK Postcode validation - John Gardner - http://www.braemoor.co.uk/software/postcodes.shtml
function checkPostCode (toCheck) {
var alpha1 = "[abcdefghijklmnoprstuwyz]";
var alpha2 = "[abcdefghklmnopqrstuvwxy]";
var alpha3 = "[abcdefghjkstuw]";
var alpha4 = "[abehmnprvwxy]";
var alpha5 = "[abdefghjlnpqrstuwxyz]";
var pcexp = new Array ();
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 + "?[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);
var postCode = toCheck;
var valid = false;
for ( var 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 ");
valid = true;
break;
}
}
if (valid) {return postCode;} else return false;
}
Short form:
// UK Postcode validation - John Gardner - http://www.braemoor.co.uk/software/postcodes.shtml
function checkPostCode(tC){var a1="[abcdefghijklmnoprstuwyz]",a2="[abcdefghklmnopqrstuvwxy]",a3="[abcdefghjkstuw]",a4="[abehmnprvwxy]",a5="[abdefghjlnpqrstuwxyz]",pX=new Array();pX.push(new RegExp("^("+a1+"{1}"+a2+"?[0-9]{1,2})(\\s*)([0-9]{1}"+a5+"{2})$","i"));pX.push(new RegExp("^("+a1+"{1}[0-9]{1}"+a3+"{1})(\\s*)([0-9]{1}"+a5+"{2})$","i"));pX.push(new RegExp("^("+a1+"{1}"+a2+"?[0-9]{1}"+a4+"{1})(\\s*)([0-9]{1}"+a5+"{2})$","i"));pX.push(/^(GIR)(\s*)(0AA)$/i);pX.push(/^(bfpo)(\s*)([0-9]{1,4})$/i);pX.push(/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);pX.push(/^([A-Z]{4})(\s*)(1ZZ)$/i);var pC=tC,v=false;for(var i=0;i<pX.length;i++){if(pX[i].test(pC)){pX[i].exec(pC);pC=RegExp.$1.toUpperCase()+" "+RegExp.$3.toUpperCase();pC=pC.replace(/C\/O\s*/,"c/o ");v=true;break;}};return(v)?pC:false;}
For further details, including annotated code, please see the original article: Validating UK post codes. Which also includes PHP and VBScript versions too.
Launch a new window in XHTML strict
author: mike foskett uploaded: 10th October 2008
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(){
if(document.getElementsByTagName){
var links=document.getElementsByTagName("a");
for(var i=links.length-1;i>-1;i--){
var 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 As=document.getElementsByTagName("a");for(var i=As.length-1;i>-1;i--){var A=As[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";}}}
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){
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':
var 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.
Shorten document.getElementById - $id()
author: mike foskett uploaded: 4th October 2008
Saves repeatedly writing out document.getElementById('idname'):
function $id(idname){
return ( document.getElementById(idname) ? document.getElementById(idname) : false );
}
Short form:
function $id(id){return(document.getElementById(id)?document.getElementById(id):false);}
Check an id exists - idExists()
author: mike foskett uploaded: 4th October 2008
Check an id actually exists prior to using it:
function idExists(idname){
return ( document.getElementById(idname) ? true : false );
}
Short form requires the $id() function too:
function idExists(id){return($id(id)?true:false);}
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 type="text/javascript">/*<![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
Setting the opacity level of an object is not yet a standard. The following snippet irons out cross-browser inconsistencies:
Original id based version:
function setOpacity(id,opacity){
var object=document.getElementById(id).style;
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;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){
for ( var exp=/-([a-z])/; exp.test(s); s=s.replace(exp, 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){for(var exp=/-([a-z])/;exp.test(s);s=s.replace(exp,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(id,p){var o=$id(id),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 = "";
if (days){
var 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 + "=";
var ca = document.cookie.split(';');
for(var i=ca.length-1; i < -1; 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 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 x="";if(d){var t=new Date();t.setTime(t.getTime()+(d*24*60*60*1000));x="; x="+t.toGMTString();}document.cookie=n+"="+v+x+";path=/";}
function readCookie(n){var m=n+"=",ca=document.cookie.split(';');for(var i=ca.length-1;i>-1;i--){var c=ca[i];while(c.charAt(0)==' '){c=c.substring(1,c.length);}if(c.indexOf(m)===0){return c.substring(m.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.
Comments…
comments opened 21st January 2010
The commenting system used here is a modified version of comment_rave.

1
mike foskett replies:
21 01 2010
Now that the spammers have been curtailed it's time this resource had comments