JAVASCRIPT TIPS AND TRICKS

How do I get the page background image to stay fixed when the page is scrolled?

The technique is called watermarking.

One simple way is to add bgproperties="fixed" to the body tag, like this:

<body  bgproperties="fixed">

Note that this typically only works in Internet Explorer browsers.

Another way of doing it that also works in later Netscape browsers (6.x & up) is to add this style script to the <head> of your page:

<style>
body 
 {background-attachment:fixed}
</style> 
                              

How do I call more than one JavaScript function in a body tag (or other) event handler?

Simple.  End each function call  with a semi-colon ;
Like this:

<body onload="someFunction();otherFunction();">

or, say, in a mouseover...

onMouseOver="someFunction();otherFunction();"

In JavaScript, the semi-colon is essentially an end-of-line marker.  Within reasonable limits, you can actually write a whole script inside of an event handler.

The same thing applies to the href="javascript:etc" structure.  For instance:

<a href="javascript:someFunction();otherFunction();">
Click Here
</a>

How do I make a window "pop under" when it is opened?

Put this as early in the <head> of the page as possible:

<script>
self.blur();
</script>

That tells the window to "lose focus" as soon as it reads the self.blur(); -- which makes the window "jump behind" the window that is currently in focus.

If you have worked with client side javascript programming then you will be well aware  about most of the below functions, tips and tricks, but believe me there are some  tested functions which you might have not worked with. Shabir Hakim

 here are what I believe to the top ten greatest custom JavaScript functions in use today.
Upon further reading this article, it is suggested that for this article in particular the reader should use an alternate style with cleaner whitespace and larger margins.

addEvent()

Surely a staple to event attachment! Regardless to what version you

use written by whatever developer, it does what it says it does. And of course as you might of known, I?ve put together quite a handy version myself recently of addEvent() with some help from the contest winner and Mark Wubben along with a few minor syntax adjustments.

addEvent() function

function addEvent(elm, evType, fn, useCapture)
{ if (elm.addEventListener)
{ elm.addEventListener(evType, fn, useCapture); return true; }
else if (elm.attachEvent)
{ var r = elm.attachEvent('on' + evType, fn); return r; }
else { elm['on' + evType] = fn; } }

addLoadEvent()

function highly adopted by many others as a simple way to add events to trigger after the page has loaded. This of course attaches all your events to the onload event handler which some still see as necessary, nevertheless it does exactly what it?s supposed to, and does it well.

addLoadEvent()

function addLoadEvent(func) { 
var oldonload = window.onload;
if (typeof window.onload != 'function') { window.onload = func; }
else { window.onload = function()
{ oldonload(); func(); } } }

Of course another method is to simply assign multiple event listeners to the window by using addEvent() as described in number 10 as follows:

assigning multiple load events to window

addEvent(window,'load',func1,false); addEvent(window,'load',func2,false); addEvent(window,'load',func3,false);

8) getElementsByClass()

Several developers have implemented their own version and no one single version has proven to be better than another. This function was spawned from developers needing a quick and elegant way of grabbing elements by a className and to a developer?s surprise, it?s not an original DOM method as one might think?after all, we have getElementById, getElementsByName(), getElementsByTagName, what the hell happened to getElementsByClass??? Here it is in all its glory:

getElementsByClass

function getElementsByClass(searchClass,node,tag) { var classElements = new Array();
    if ( node == null ) node = document; if ( tag == null ) tag = '*'; 
var els = node.getElementsByTagName(tag); var elsLen = els.length; var pattern = new RegExp('(^|\\s)'+searchClass+'(\\s|$)'); for (i = 0, j = 0; i < elsLen; i++) { if ( pattern.test(els[i].className) ) { classElements[j] = els[i]; j++; } } return classElements; }

Simply add a class name to the beginning of the function and the 2nd and 3rd arguments are optional and the magic is done for you!

7) cssQuery()

Way to query the DOM according to CSS properties which supports a multitude of selectors. However in all fairness, this is more like a mini-library and not quite so light on the weight factor, but still, a very kick-ass function. Due to its length (and CC licensing) I won?t post it on this site.

6) toggle()

To be totally honest, there are probably more variations of this function than there needs to be. The history of ?toggling? basically comes down to showing/hiding an element upon an event being fired. To make matters much simpler, I too have put one together. But by no means is it considered the ultimate toggle function, but it does do the basic functionality of showing and hiding.

toggle()

function toggle(obj) { var el = document.getElementById(obj); if ( el.style.display
    != 'none' ) { el.style.display = 'none'; } else { el.style.display = ''; } }

5) insertAfter()

This is just like getElementsByClass, it isn?t. So rather than pulling the function straight out of the book.

insertAfter() on public domain

function insertAfter(parent, node, referenceNode) { parent.insertBefore(node,
    referenceNode.nextSibling); }

4) inArray()

This too is very sad that this isn?t part of the DOM core functionality. But hey, it makes for fun references like this! This function however isn?t quite a function; it?s a prototype that extends the DOM Array object. I remember one day thinking to myself ?surely I can do this in PHP, it?s gotta be in JavaScript.? Well, this extension makes it work just like you?d expect if you?re a PHP developer.

inArray Prototype Array object

Array.prototype.inArray = function (value) { var i; for (i=0; i < this.length;
    i++) { if (this[i] === value) { return true; } } return false; };

3, 2, & 1) getCookie(), setCookie(), deleteCookie()

I honestly don?t know what I would do without these guys. I hate the DOM implementations of setting cookies in JavaScript. In PHP it?s so easy, and it?s easy for one main reason, they work just like the functions below. All three of these functions were found to be public domain and free to use.

getCookie(), setCookie(), deleteCookie() open domain

function getCookie( name ) 
{ var start = document.cookie.indexOf( name + "=" ); var len = start + name.length + 1;
if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ))){ return null; } if ( start == -1 )
return null; var end = document.cookie.indexOf( ';', len );
if ( end == -1 ) end = document.cookie.length;
return unescape( document.cookie.substring( len, end ) ); } function setCookie( name, value, expires, path, domain, secure ) { var today = new Date(); today.setTime( today.getTime() ); if ( expires ) { expires = expires * 1000 * 60 * 60 * 24; } var expires_date = new Date( today.getTime() + (expires) ); document.cookie = name+'='+escape( value ) + ( ( expires ) ? ';
expires='+expires_date.toGMTString() : '' )+ ( ( path ) ? ';path=' + path : '' ) + ( ( domain ) ? ';domain=' + domain : '' ) + ( ( secure ) ? ';secure' : '' ); } function deleteCookie( name, path, domain ) { if ( getCookie( name ) ) document.cookie = name + '=' + ( ( path ) ? ';path=' + path : '') + ( ( domain ) ? ';domain=' + domain : '' ) + ';
expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

The Prototype Dollar Function

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; 
if (typeof element == 'string') element = document.getElementById(element); if (arguments.length == 1) return element;
elements.push(element); } return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() { var i;
var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

Tell me that?s not beautiful! Short not only by name, but by reference. It not only takes in strings, it takes objects too. You can pass it one argument, or pass it many! This by far is my favorite function of all time which will provide years and years of handiness.

JavaScript triggers

The simplest JavaScript trigger is the id attribute:
<div id="navigation"> <ul> <li><a href="#">Link 1</a></li>
    <li><a href="#">Link 2</a></li> <li><a href="#">Link
    3</a></li> </ul> </div>
var x = document.getElementById('navigation'); if (!x) return; var y = x.getElementsByTagName('a');
for (var i=0;i<y.length;i++) y[i].onmouseover = addBehavior;


Unfortunately there are situations where you can?t use id as a trigger:
  1. An id can be used only once in a document, and sometimes you want to add the same behavior to several (groups of) elements.
  2. Occasionally a script needs more information than just ?deploy behavior here.?

Let?s take form scripts as an example of both problems. It would be useful to add form validation triggers to the XHTML, for instance something that says ?this field is required.? If we?d use such a trigger we?d get a simple script like the one below.

Advanced triggers

function validateForm() 
{ var x = document.forms[0].elements; for (var i=0;i<x.length;i++) { if ([this field is required] && !x[i].value) // notify user of error } }


But how do we create an XHTML trigger that tells the script a certain field is required? Using an id isn?t an option: we need a solution that works on an unlimited amount of form fields. It would be possible to use the class attribute to trigger the behavior:
<input name="name" class="required" /> if (x[i].className == 'required'
    && !x[i].value) // notify user of error 

However, the class attribute?s proper use is defining CSS triggers. Combining CSS and JavaScript triggers is not impossible, but it can quickly lead to a confused jumble of code:

<input name="name" class="largefield required" /> 
if ( x[i].className.indexOf('required') != -1 && !x[i].value )


Besides, triggers can grow to be more complicated than just a ?deploy behavior here? command. Sometimes you?ll want to add a value to the trigger. A trigger value would make the behavior layer much more versatile, since it can now respond to each XHTML element?s individual requirements instead of mindlessly executing a standard script.

Take a form in which some textareas have a maximum length for their value. The old MAXLENGTH attribute doesn?t work on textareas, so we have to write a script. In addition, not all textareas in the form have the same maximum length, making it necessary to store the maximum length of each individual textarea somewhere.

We want something like this:

Information-carrying triggers

var x = document.getElementsByTagName('textarea'); for (var i=0;i<x.length;i++)
    { if ([this textarea has a maximum length]) x[i].onkeypress = checkLength;
    } function checkLength() { var max = [read out maximum length];
    if (this.value.length > max) // notify user of error } 


The script needs two bits of information:
  1. Does this textarea have a maximum length? This is the general trigger that alerts the script that some behavior is coming up.
  2. What is the maximum length? This is the value the script needs to properly check user input.

And it is here that the class-based solution doesn?t really serve any more. Technically it?s still possible, but the necessary code becomes too complicated. Take a textarea with a CSS class "large" that is required and has a maximum length of 300 characters:

<textarea class="large required maxlength=300"> </textarea> 

Not only does this example mix presentation and two separate sets of behavior, it also becomes tricky to read out the actual maximum length of the textarea:

var max = this.className.substring( this.className.indexOf('maxlength')+10 );
if (this.value.length > max) // notify user of error

Note that this bit of code works only when we put the maxlength trigger last in the class value. If we want to allow a maxlength trigger anywhere in the class value (because we want to add another trigger with a value, for instance) the code becomes even more complicated.

The problem

So this is our problem for today. How do we add good JavaScript triggers that allow us to pass both a general alert (?deploy behavior here?) and an element-specific value to the script?

Technically, adding this information to the class attribute is possible, but is it allowed to use this attribute for carrying information it was not designed to carry? Does this violate the separation of behavior and presentation? Even if you feel there is no theoretical obstacle, it remains a complicated solution that requires complicated JavaScript code.

It is also possible to add the trigger to other existing attributes like lang or dir, but here, again, you?d use these attributes to carry information they aren?t designed for.

Custom attributes

I opt for another solution. Let?s take a second look at the textarea maxlength example. We need two bits of information:

  1. Does this textarea have a maximum length?
  2. What is the maximum length?

The natural, semantic way to express this information is to add an attribute to the textarea:

<textarea class="large" maxlength="300" > </textarea> 

The presence of the maxlength attribute alerts the script to check user input in this textarea, and it can find the maximum length of this specific textarea in the value of the attribute. As long as we?re at it we can port the ?required? trigger to a custom attribute, too. required="true", for instance, though any value will do because this trigger just gives a general alert and doesn?t carry extra information.

<textarea class="large" maxlength="300" required="true" > </textarea>

Technically there?s no problem. The W3C DOM getAttribute() method allows us to read out any attribute from any tag. Only Opera up to version 7.54 doesn?t allow us to read out existing attributes (like src) on the wrong tag (like <h2>). Fortunately later versions of this browser support getAttribute() fully.

So this is my solution:

function validateForm() { var x = document.forms[0].elements; for (var i=0;i<x.length;i++)
    { if (x[i].getAttribute('required') && !x[i].value) //
    notify user of error } } var x = document.getElementsByTagName('textarea'); for
    (var i=0;i<x.length;i++) { if (x[i].getAttribute('maxlength'))
    x[i].onkeypress = checkLength; } function checkLength() { var max = this.getAttribute('maxlength');
    if (this.value.length > max) // notify user of error } 

In my opinion this solution is easy to implement and consistent with the form JavaScript triggers may take: a name/value pair where the presence of the name triggers the behavior and the value gives the script extra information, allowing you to customize the behavior for each individual element. Finally, adding these triggers to the XHTML would be extremely simple even for novice webmasters.

Prototype function $

function $() { var elements = new Array();
for (var i = 0; i < arguments.length; i++) { var element = arguments[i]; if (typeof element == 'string')
element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element);
} return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() { var i;
var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string')
element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element);
} return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() {
var i; var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); 
for (var i = 0; i < arguments.length; i++) { var element = arguments[i]; if (typeof element == 'string')
element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); }
return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() { var i;
var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array();
for (var i = 0; i < arguments.length; i++) { var element = arguments[i]; if (typeof element == 'string')
element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element);
} return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() { var i;
var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i];
if (typeof element == 'string')
element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element);
} return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements()
{ var i; var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string')
element = document.getElementById(element); if (arguments.length == 1) return element;
elements.push(element); } return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements()
{ var i; var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') 
element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element);
} return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') 
element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); } return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') 
element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element);
} return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() { var i;
var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

 Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') 
element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); }
return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') 
element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element);
} return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string')
element = document.getElementById(element); if (arguments.length == 1) return element;
elements.push(element);
} return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); 
for (var i = 0; i < arguments.length; i++) { var element = arguments[i];
if (typeof element == 'string')
element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); }
return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() { var i;
var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array();
for (var i = 0; i < arguments.length; i++) { var element = arguments[i];
if (typeof element == 'string')
element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); }
return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); 
for (var i = 0; i < arguments.length; i++) { var element = arguments[i]; if (typeof element == 'string')
element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); }
return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() { var i;
var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i];
if (typeof element == 'string') element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); }
return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() { var i;
var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string')
element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); }
return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() { var i;
var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array();
for (var i = 0; i < arguments.length; i++) { var element = arguments[i]; if (typeof element == 'string')
element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element);
} return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array();
for (var i = 0; i < arguments.length; i++) { var element = arguments[i]; if (typeof element == 'string')
element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); }
return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array();
for (var i = 0; i < arguments.length; i++) { var element = arguments[i]; if (typeof element == 'string')
element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element);
} return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() { var i;
var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array();
for (var i = 0; i < arguments.length; i++) { var element = arguments[i]; if (typeof element == 'string')
element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); }
return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() { var i;
var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string')
element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); }
return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() { var i;
var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string')
element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); }
return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() { var i;
var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') 
element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); }
return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

oThis function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); 
for (var i = 0; i < arguments.length; i++) { var element = arguments[i]; if (typeof element == 'string')
element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); }
return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
    if (arguments.length == 1) return element; elements.push(element); } return elements;
    } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2');
    function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e');
    for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
    if (arguments.length == 1) return element; elements.push(element); } return elements;
    } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2');
    function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e');
    for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
    if (arguments.length == 1) return element; elements.push(element); } return elements;
    } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2');
    function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e');
    for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
    if (arguments.length == 1) return element; elements.push(element); } return elements;
    } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2');
    function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e');
    for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
    if (arguments.length == 1) return element; elements.push(element); } return elements;
    } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2');
    function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e');
    for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
    if (arguments.length == 1) return element; elements.push(element); } return elements;
    } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2');
    function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e');
    for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
    if (arguments.length == 1) return element; elements.push(element); } return elements;
    } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2');
    function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e');
    for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
    if (arguments.length == 1) return element; elements.push(element); } return elements;
    } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2');
    function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e');
    for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
    if (arguments.length == 1) return element; elements.push(element); } return elements;
    } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2');
    function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e');
    for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
    if (arguments.length == 1) return element; elements.push(element); } return elements;
    } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2');
    function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e');
    for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
    if (arguments.length == 1) return element; elements.push(element); } return elements;
    } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2');
    function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e');
    for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
    if (arguments.length == 1) return element; elements.push(element); } return elements;
    } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2');
    function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e');
    for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
    if (arguments.length == 1) return element; elements.push(element); } return elements;
    } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2');
    function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e');
    for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
    if (arguments.length == 1) return element; elements.push(element); } return elements;
    } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2');
    function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e');
    for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
    if (arguments.length == 1) return element; elements.push(element); } return elements;
    } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2');
    function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e');
    for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() 
{ var elements = new Array();
for (var i = 0; i < arguments.length; i++)
{ var element = arguments[i];
if (typeof element == 'string')
element = document.getElementById(element); if (arguments.length == 1)
return element; elements.push(element); }
return elements; } // Sample Usage:
var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() {
var i; var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array();
for (var i = 0; i < arguments.length; i++)
{ var element = arguments[i]; if (typeof element == 'string')
element = document.getElementById(element); if (arguments.length == 1)
return element; elements.push(element); }
return elements; } // Sample Usage:
var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements()
{ var i; var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') 
element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); }
return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
    if (arguments.length == 1) return element; elements.push(element); } return elements;
    } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2');
    function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e');
    for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); 
for (var i = 0; i < arguments.length; i++)
{ var element = arguments[i];
if (typeof element == 'string')
element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); }
return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
    if (arguments.length == 1) return element; elements.push(element); } return elements;
    } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2');
    function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e');
    for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
    if (arguments.length == 1) return element; elements.push(element); } return elements;
    } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2');
    function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e');
    for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
    if (arguments.length == 1) return element; elements.push(element); } return elements;
    } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2');
    function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e');
    for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
    if (arguments.length == 1) return element; elements.push(element); } return elements;
    } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2');
    function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e');
    for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
    if (arguments.length == 1) return element; elements.push(element); } return elements;
    } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2');
    function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e');
    for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
    if (arguments.length == 1) return element; elements.push(element); } return elements;
    } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2');
    function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e');
    for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
    if (arguments.length == 1) return element; elements.push(element); } return elements;
    } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2');
    function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e');
    for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
    if (arguments.length == 1) return element; elements.push(element); } return elements;
    } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2');
    function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e');
    for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) 
{ var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); } return elements; } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2'); function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++)
{ var element = arguments[i];
if (typeof element == 'string') element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); }
return elements; } // Sample Usage: var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2'); function alertElements()
{ var i; var elements = $('a','b','c',obj1,obj2,'d','e'); for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

function $() { var elements = new Array(); for (var i = 0; i < arguments.length;
    i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
    if (arguments.length == 1) return element; elements.push(element); } return elements;
    } // Sample Usage: var obj1 = document.getElementById('element1'); var obj2 = document.getElementById('element2');
    function alertElements() { var i; var elements = $('a','b','c',obj1,obj2,'d','e');
    for ( i=0;i<elements.length alert="" code="" elements[i].id="" i=""></elements.length>

How can I set a window's size when it is opened?

Put this as early in the <head> of the page as possible:

<script>
self.resizeTo(100,200);
</script>

Set the dimensions in the parentheses.  The first number is the width; the second is the height.

How can I set a window's position when it is opened?

Put this as early in the <head> of the page as possible:

<script>
self.moveTo(100,200);
</script>

Set the position in the parentheses.  The first number is the x (that is, left) position; the second number is the y (that is, top) position.

How can I make certain a window will "come to the front" when it is loaded?

Add onload="self.focus();" to the body tag, like this:

<body onload="self.focus();">

As soon as the window is fully loaded, it will "take focus" and move in front of any other open windows.

How can I stop a window from "losing focus" -- hiding behind other windows?

Add onblur="self.focus();" to the body tag, like this:

<body onblur="self.focus();">

Use this with some forethought, as it acts like a modal window, pre-empting focus until it is closed.

How can I make a window periodically come to the front if it has lost focus?

You can use a timer to call self.focus() for this, that is triggered whenever the window loses focus by detecting the onblur event.  Add onBlur="setTimeout('self.focus()',500)"  to the window's body tag, like this:

<body onBlur="setTimeout('self.focus()',500)">

The 500 is the time interval, in milliseconds. (1000 milliseconds is 1 second).  Usually a range of 300-7000 will keep the window comfortably in front.  Unlike a simple onblur="self.focus();" shown above, the window does not behave modally.

How can I prevent a page from being captured in someone else's frameset?

The technique is called frame busting .  Put the following script in the head of the page:

<script>
if (window!=top){top.location.href=location.href;}
</script>

Whenever the page loads, it checks to see if it is in a frameset (that is, not the "top" window).  If it is, it reloads itself as topmost.

.

How can I redirect a page to a different address, even if the user has JavaScript turned off?

Use suspenders and a belt -- both the Refresh pragma and a JavaScript redirect in the <head> of the page, like this:

  <meta http-equiv="Refresh" content="0; url=http://www.mysite.com/mypage.html">
<script>
window.location="http://www.mysite.com/mypage.html";
</script>
Make sure to set both url's the same, and be careful of the punctuation in the Refresh pragma

The other way to do this is server-side via the .htaccess file in your web root.  Do this with caution, and always check your server documentation or with your server administrator to be certain it's allowed on your host -- though the technique is very much standard on UNIX/LINUX boxes. Add a Redirect request to your .htaccess file in the following general form: Redirect whatpage.html http://www.mysite.com/otherpage.html In this example, whatpage.html is redirected to http://www.mysite.com/otherpage.html.

How can I make a page reload itself at a given time interval?

Generally this is done with the Refresh pragma.  Put this in the <head> of the page:

                                <meta http-equiv="Refresh" content="60; url=http://www.mysite.com/mypage.html">
                                The 60 in the sample code is the time interval, set in seconds.  For the url,
                                use the address of the page that is refreshing itself.

How do I stop the scrollbar from showing in a regular window?

In windows where you have a minimum of content, or for design reasons do not want the browser scrollbar to show, you can remove the scrollbar by adding scroll="no" to the page body tag, like this:

                                <body scroll="no">
                            

A perhaps more sensible approach in most cases, however, is to use scroll="auto" instead.  This removes the scrollbar from the page when there is no need for it; but shows the scrollbar when content exceeds the length of the window.  Thus:

                                <body scroll="auto">

How do I attach more than one style to an element?

Basically, you just put them all in a row with a space between them when you attach the class, as in this <div> example, where three different styles are used:

                                <div class="styleOne styleTwo styleThree">

For instance, let's say we have this style script in the head of the page:

<style>

.bigText {
font-family: sans-serif;
font-size: 20px;
}

.redItalic {
color : red;
font-style: italic;
}

.lineThrough {
text-decoration: line-through;
}

</style>

To attach that to a <div> with some text, it would look like this:

<div class="bigText redItalic lineThrough">
The dogs of war eat watermelons.
</div>

with the result showing, thus...

The dogs of war eat watermelons.

If you think this through a bit, it can greatly simplify the use of styles, by segregating particular characteristics to individual styles that are then combined as needed -- rather than making numerous, longer, more complex styles for every possible combination of characteristics.

How do I use a JavaScript link to return to the previous page?

JavaScript includes what is called a history object.  It tracks the URLs visited by the browser. You can use this browser history as a means to return to the previous page (or, for that matter, to go back and forward through the history). This is especially useful when a hard-coded, specific link is not possible; for instance, in cases where you do not necessarily know the address of the previously visited page.  This is how a "previous page" or "go-back" link would appear in your HTML code:

<a href="javascript:history.go(-1)">
Go Back
</a>

Alternatively, if you wanted to go forward instead of backward in the history, you would write the code thus:

<a href="javascript:history.go(1)">
Go Forward
</a>

The numbers in the parentheses are the number of pages to move (forward or back, respectively, in the above examples).  You can also move more than one page; for instance javascript.history.go(-3) would navigate three pages back in the history.  Note that if there is no page in the history to go to, the JavaScript does not error out; it

How can I protect my page code with a no-right-click script?

One of the more commonly asked questions, you will find a couple of good scripts for this at the following links:

Basic No-Right-Click Script with Alert is a standard no-right-click script.

No-Right-Click Script Launches PopUp Window is a bit more interesting, in that it launches a popup window where you can put your own page, hurling whatever invective amuses you at the unduly curious.

It should be noted that no-right-click scripts offer limited protection in a standard browser window, since the visitor can simply use View > Source from the browser menu to see the code.  However, if you put your content in a configured window (popup window, or fullscreen mode window) with no menu or status bars, such scripts can be reasonably effective.  The code for any page is still in the browser cache on the visitor's hard drive, but extremely few people will go to the effort to dig it out.

How do I close a  regular window with a JavaScript link,

and how would I do it if I am using frames?

For a regular window, use this:

<a href="javascript:window.close()">Close</a>

If you are using a frameset, then use this in any page in any frame in the frameset:

<a href="javascript:top.window.close()">Close</a>

How do I get the page background image to stay fixed when the page is scrolled?

The technique is called watermarking.

One simple way is to add bgproperties="fixed" to the body tag, like this:

<body bgproperties="fixed">

Note that this typically only works in Internet Explorer browsers.

Another way of doing it that also works in later Netscape browsers (6.x & up) is to add this style script to the <head> of your page:

<style>body {background-attachment:fixed}</style>

How do I call more than one JavaScript function in a body tag (or other) event handler?

Simple.  End each function call  with a semi-colon ;Like this:

<body <font color="#cc3300">onload="someFunction();otherFunction();">

or, say, in a mouseover...

onMouseOver="someFunction();otherFunction();"

In JavaScript, the semi-colon is essentially an end-of-line marker.

 Within reasonable limits, you can actually write a whole script inside of an event handler.

The same thing applies to the href="javascript:etc" structure.  For instance:

<a href="javascript:someFunction();otherFunction();">Click Here</a>

How do I make a window "pop under" when it is opened?

Put this as early in the <head> of the page as possible:

<script>self.blur();
                                </script>

That tells the window to "lose focus" as soon as it reads the self.blur();

-- which makes the window "jump behind" the window that is currently in focus.

How can I set a window's size when it is opened?

Put this as early in the <head> of the page as possible:

<script>self.resizeTo(100,200);</script>

Set the dimensions in the parentheses.  The first number is the width; the second

 is the height.

How can I set a window's position when it is opened?

Put this as early in the <head> of the page as possible:

<script>self.moveTo(100,200);</script>

Set the position in the parentheses.  The first number is the x (that is, left) position; the second number is the y (that is, top) position.

How can I make certain a window will "come to the front" when it is loaded?

Add onload="self.focus();" to the body tag, like this:

<body onload="self.focus();">

As soon as the window is fully loaded, it will "take focus" and move in front of

any other open windows.

How can I stop a window from "losing focus" -- hiding behind other windows?

Add onblur="self.focus();" to the body tag, like this:

<body onblur="self.focus();">

Use this with some forethought, as it acts like a modal window, pre-empting focus until it is closed.

How can I make a window periodically come to the front if it has lost focus?

You can use a timer to call self.focus() for this, that is triggered whenever the

window loses focus by detecting the onblur event.

  Add onBlur="setTimeout('self.focus()',500)"  to the window's body tag, like this:

<body onBlur="setTimeout('self.focus()',500)">

The 500 is the time interval, in milliseconds. (1000 milliseconds is 1 second). 

 Usually a range of 300-7000 will keep the window comfortably in front.  Unlike a simple onblur="self.focus();" shown above, the window does not behave modally.

 

How can I prevent a page from being captured in someone else's frameset?

The technique is called frame busting.  Put the following script in the head of the page:

<script>if (window!=top){top.location.href=location.href;}</script>

Whenever the page loads, it checks to see if it is in a frameset (that is, not the "top" window).  If it is, it reloads itself as topmost.

How can I redirect a page to a different address, even if the user has JavaScript turned off?

Use suspenders and a belt -- both the Refresh pragma and a JavaScript redirect in the <head> of the page, like this:

<meta http-equiv="Refresh" content="0; url=http://www.mysite.com/mypage.html"><script>window.location="http://www.mysite.com/mypage.html";</script>

Make sure to set both url's the same, and be careful of the punctuation in the Refresh pragma.

The other way to do this is server-side via the .htaccess file in your web root.  Do this with caution,

and always check your server documentation or with your server administrator to be certain

it's allowed on your host -- though the technique is very much standard on UNIX/LINUX boxes.

Add a Redirect request to your .htaccess file in the following general form:

Redirect whatpage.html http://www.mysite.com/otherpage.html

In this example, whatpage.html is redirected to http://www.mysite.com/otherpage.html.

How can I make a page reload itself at a given time interval?

Generally this is done with the Refresh pragma.  Put this in the <head> of the page:

<meta http-equiv="Refresh" content="60; url=http://www.mysite.com/mypage.html">

The 60 in the sample code is the time interval, set in seconds.  For the url,

use the address of the page that is refreshing itself.

How do I stop the scrollbar from showing in a regular window?

In windows where you have a minimum of content, or for design reasons do not want

 the browser scrollbar to show, you can remove the scrollbar by adding scroll="no"

to the page body tag, like this:

<body scroll="no">

A perhaps more sensible approach in most cases, however, is to use scroll="auto"

instead.  This removes the scrollbar from

the page when there is no need for it; but shows the scrollbar when content

 exceeds the length of the window.  Thus:

<body scroll="auto">

How do I attach more than one style to an element?

Basically, you just put them all in a row with a space between them when you attach the

 class, as in this <div> example, where three different styles are used:

<div class="styleOne styleTwo styleThree">

For instance, let's say we have this style script in the head of the page:

<style>.bigText {font-family: sans-serif;font-size: 20px;}.redItalic {color : red;font-style: italic;}.lineThrough {text-decoration: line-through;}</style>

To attach that to a <div> with some text, it would look like this:

<div class="bigText redItalic lineThrough">The dogs of war eat watermelons.</div>

with the result showing, thus...

The dogs of war eat watermelons.

If you think this through a bit, it can greatly simplify the use of styles, by segregating

 particular characteristics to individual styles that are then combined as needed -- rather

 than making numerous, longer, more complex styles for every possible combination of

 characteristics.

How do I use a JavaScript link to return to the previous page?

JavaScript includes what is called a history object.  It tracks the URLs

visited by the browser. You can use this browser history as a means to return to the previous page (or, for that matter, to go back and forward through the history). This is especially useful when a hard-coded, specific link is not possible; for instance, in cases where you do not necessarily know the address of the previously visited page.  This is how a "previous page" or "go-back" link would

 appear in your HTML code:

<a href="javascript:history.go(-1)">Go Back</a>

Alternatively, if you wanted to go forward instead of backward in the history, you would write

the code thus:

<a href="javascript:history.go(1)">Go Forward</a>

The numbers in the parentheses are the number of pages to move (forward or back, respectively,

in the above examples).  You can also move more than one page; for instance

javascript.history.go(-3) would navigate three pages back in the history.  Note that if there

is no page in the history to go to, the JavaScript does not error out; it simply does nothing. 

How can I protect my page code with a no-right-click script?

One of the more commonly asked questions, you will find a couple of good scripts for this at

 the following links:

Basic No-Right-Click Script with Alert is a standard no-right-click script.

No-Right-Click Script Launches PopUp Window is a bit more interesting, in that it launches a popup

 window where you can put your own page, hurling whatever invective amuses you at the unduly

curious.

It should be noted that no-right-click scripts offer limited protection in a standard browser

window, since the visitor can simply use View > Source from the browser menu to see the code.

  However, if you put your content in a configured window (popup window,

or fullscreen mode window) with no menu or status bars, such scripts can be reasonably effective.  The code for any page is still in the browser cache on

the visitor's hard drive, but extremely few people will go to the effort to dig it out.

How do I close a  regular window with a JavaScript link, and how would I do it if

I am using frames?

For a regular window, use this:

<a href="javascript:window.close()">Close</a>

If you are using a frameset, then use this in any page in any frame in the frameset:

<a href="javascript:top.window.close()">Close</a>

Avoid having your pages open into someone else's frame

If you want to protect your pages from being opened within a frame, use the following script:

<SCRIPT>if (self != top)top.location = self.location</SCRIPT>

This code checks to see if this page is the top page (i.e., that its being loaded into the original window rather than into a frame). If it isn't, the page is set to load into the original window.

Further to this...'At times, site frames can be useful, but when they don't clear themselves from your browser when you click on "outside" links, they become annoying. So, next time this happens in IE4, simply click (and hold) a link, then drag & drop it onto the address line of your browser. Voila -- no more frames! You may also drag & drop links into folders or onto your Desktop; it's a link's greatest adventure.'


Auto-updating

Want to add an auto-updating splash page? Simply open the Page Properties dialogue box, then select the Custom Tab and then the Add button.  Under Name, type in "refresh", then under "value" enter "10;URL=http://www.yourwebsite.com/" where "10" is then the number of seconds before it redirects to the new location.


Tip 4    Text colour change onMouseOver.

Open your page in FrontPage. Choose the 'HTML View'. Create a new blank line above the <\head> tag.

Insert the code below and OK out.<style><!--a:hover{color:red;} // --></style>

You can change the colour to what you want e.g. Green.or if you want different colours for different links you can do it this way...

<style><!--a.one {color: black}--></style><style><!--a.two {color:blue}--></style>

Then for your individual links in the body do this.<p><a class="one" href="http://www.myfaithsolution.com">http://www.myfaithsolution.com</a></p>

<p><a class="two" href="http://www.test.com">http://www.test.com</a></p>

This will give you separate colours for each.

Pop up text box or Tool Tip

Small yellow pop-up messages that appear to explain the function of a button in most windows applications can be made to appear on your website.  Using the 'title' tag. This is designed to be used as explanatory system for little-known acronyms.  For example, the code.

<A title="What You See Is What You Get">WYSIWYG</A>

WYSIWYG Put your cursor over wysiwyg to the left and watch an explanation pop up, viewable only in IE.

Or you can use this in conjunction with a hyperlink like so:

<A href="http://anyfrontpage.com/bytes/" title="The FrontPage Ezine of Choice!!">

AnyFrontPage Bytes Ezine   << Mouseover


NoSpam thankee Mam

The HTML Encoder is a service of SiteUp Networks. The Encoder will format your E-mail address in a way that IS NOT readable by any E-mail extractor or search engine. Just enter your E-mail and click the Encode button.  Your SPAM proof address will arrive in your Inbox in a few minutes.NOTE: you do not need to subscribe to their newsletters.


How to make a website your home page

<a href="#" onClick="this.style.behavior='url(#default#homepage)';this.setHomePage('http://.net');">

Click here to make AccessFP your default homepage</a>

Substitute the URL and change 'Click here to make AccessFP your default homepage' to what

 ever text you would like. Put the code wherever you want on the website and it should work.


Bookmark this page

Would you like your visitors to book mark pages in your your site? Enter the below code

anywhere you want it to appear, Change the text 'BookMark' to whatever you want to appear.

BookMark Click this link to check out the code

<a HREF=index.html#&quot; ONDRAGSTART="return false" ONCLICK="window.external.AddFavorite(location.href, document.title);return false" ONMOUSEOVER="window.status='Add to Favorites';return true">BookMark</a>

NOTE: Copy and paste to NOTEPAD before entering into the html view.This will only work in Internet Explorer if other browsers press control + D


How to recommend a friend

<span onclick="location='mailto:?subject='+top.document.title+'&amp;body=Hi, just visited this page at '+top.location.host+' and

wanted to share it with you, take a look:

'+top.document.location+''"style="CURSOR: hand" )>Recommend A Friend</span>

Insert the above where you want the link to appear, the bits you can edit are in red.


How to make an email link pop up with a message in the subject line and the body configured. The Cc or Bcc as well if you want! Can be used for Netscape or IE.

Example code

mail@myfaithsolution.com?Subject=Web Site Feedback&Body=Hi, I am just testing your tip&CC=mail@myfaithsolution.com

Example Link

Email the Webmaster

Type the text you wish to use as link for your Email link. e.g. "Email the Webmaster".

Click on 'Hyperlink' under 'Edit' from the toolbar or click the 'Hyperlink icon'. Click

on the mail icon shaped like an envelope in the 'Create Hyperlink' box that pops up. In

the new box named 'Create an E-mail Hyperlink' that pops up enter the following:

After you have entered your email address e.g.

"abc@usa.net" (without the quotes).Next you type  " ?Subject= " (without the quotes)Enter the text you wish to appear in the 'Subject line' e.g. "Web Site Feedback"

 (without the quotes).

Then you add " &Body= " (without the quotes).

Next you type the text you wish to enter for example "Hi, I am just testing this tip"

(without the quotes).If also want to include Bcc or Cc your just enter the ....  &   .... command for

those as well. Make sure the commands are inserted flush against the the last entry as

 you can see in the code above.

Also depending on your email setup you can substitute your usual name before the @.

For instance Feedback@access.net. Instead of faith which I usually use. This way

you can channel emails for different aspects of your life. For instance you might want

 to use Newsgroups with NG Feedback so that you know for certain that is where your

 feedback is coming from. This can be used for any aspect of your web presence.


How to track your URL

http://.net/index.htm?1

By inserting the ?1 after the URL when you look at your stats you can determine how

often this URL at the source you left it at is accessed. This is great for people in

business who want to track how a particular promotion is doing. You can insert anything

after the ? the URL takes you to the normal page, it just shows up in your stats enabling

you to take count.


Breaking outta that frame-up

Stuck in another site's frames? Click here to break out! ....if you copy this code

 into your html view at the point you want it to be inserted you can help your

visitors come unstuck they will thank you for it. Also see below for tip that applies

to Tip 1 as well.

<a href="http://.net/" target="_top">Stuck in another site's frames? Click

here to break out!</a>

Stuck in another site's frames? Click here to break out!

Further to this...'At times, site frames can be useful, but when they don't clear

 themselves from your browser when you click on "outside" links, they become annoying.

 So, next time this happens in IE4+, simply click (and hold) a link, then drag & drop

it onto the address line of your browser. Voila -- no more frames! You may also drag & drop links into folders or onto your Desktop; it's a link's greatest adventure.'


Point the way

If you want to point to another page on your web you just enter the URL right?...

E.G. if I want to go from wdt.htm to newbies2.htm I just enter newbies2.htm in the

'Edit Hyperlink box'. However if I wish to go to a certain point on the page at newbies2.htm this is what I do.

On the page named wdt.htm Enter text (for example) ...Images/graphics help:... at

the point you wish to insert it. Then Highlight the text you just wrote and press

bookmark and enter the text (for example) ...Web DesignTools... (this text is not

the same as what you have just written so don't forget and just do it automatically

you have to enter new text) which as you can see above was (for example) ...Web DesignTools...

Next go to Newbies2.htm and at the point you wish to insert the text enter ...Web DesignTools...Then Highlight the text you just wrote and press bookmark and enter the

 text (for example) ...Images/graphics help:...

Next highlight the text ...Web DesignTools... Click the 'Edit Hyperlink button' and

 enter into the 'URL box' ...wdt.htm#Images/graphics help:...Next Go to Wdt.htm and highlight the text ...Images/graphics help:... Click the 'Edit

Hyperlink button' and enter into the 'URL box' ...newbies2.htm#Web DesignTools...Save both your pages and publish to the web. If you want to see this working in action first, then goto:

http://.net/wdt.htm

and

http://.net/newbies2.htm

Your visitors won't then have to search for what your referring to.


 Index or not to index that is the question

If you have a page that you don't want to be indexed, use this tag:

     <META NAME="ROBOTS" CONTENT="noindex,nofollow">

However, not all search engines support this tag.


Pop up a pop up

Want to open a pop up window when the page loads? Here is the code to do it.

<SCRIPT LANGUAGE="javascript">window.open('yourpage.htm', 'yourpage', config='height=50,width=50'</SCRIPT>


Click to Print

Would you like to have a clickable link that viewers could use to print

 your pages? If so insert the below code in-between your body tags.

<a href="#" onClick="window.print()">Print this page</a>

 
function addEvent(elm, evType, fn, useCapture) {
	if (elm.addEventListener) {
		elm.addEventListener(evType, fn, useCapture);
		return true;
	}
	else if (elm.attachEvent) {
		var r = elm.attachEvent('on' + evType, fn);
		return r;
	}
	else {
		elm['on' + evType] = fn;
	}
}

addLoadEvent()

Originally written by Simon Willison and highly adopted by many others as a simple way to add events to trigger after the page has loaded. This of course attaches all your events to the onload event handler which some still see as necessary, nevertheless it does exactly what it?s supposed to, and does it well.

addLoadEvent() by Simon Willison

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

Of course another method is to simply assign multiple event listeners to the window by using addEvent() as described in number 10 as follows:

assigning multiple load events to window

addEvent(window,'load',func1,false);
addEvent(window,'load',func2,false);
addEvent(window,'load',func3,false);

getElementsByClass()

Originially written by nobody in particular. Several developers have implemented their own version and no one single version has proven to be better than another. As you might expect, my humble self has even had a crack at it. This function was spawned from developers needing a quick and elegant way of grabbing elements by a className and to a developer?s surprise, it?s not an original DOM method as one might think?afterall, we have getElementById, getElementsByName(), getElementsByTagName, what the hell happened to getElementsByClass??? Here it is in all its glory:

getElementsByClass by Dustin Diaz

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp('(^|\\s)'+searchClass+'(\\s|$)');
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

Simply add a class name to the beginning of the funciton and the 2nd and 3rd arguments are optional and the magic is done for you!

cssQuery()

Originally written by Dean Edwards as a way to query the DOM according to CSS properties which supports a multitude of selectors. However in all fairness, this is more like a mini-library and not quite so light on the weight factor, but still, a very kick-ass function. Due to its length (and CC lisencing) I won?t post it on this site. Full documentation can be found on the myCssQuery reference and download page.

toggle()

To be totally honest, there are probably more variations of this function than there needs to be. The history of ?toggling? basically comes down to showing/hiding an element upon an event being fired. To make matters much simpler, I too have put one together. But by no means is it considered the ultimate toggle function, but it does do the basic functionality of showing and hiding.

toggle() by the masses

function toggle(obj) {
	var el = document.getElementById(obj);
	if ( el.style.display != 'none' ) {
		el.style.display = 'none';
	}
	else {
		el.style.display = '';
	}
}

insertAfter()

As far as I know, Jeremy Keith sort of came up with this idea even though one would have thought this too would be a DOM core method. But just like getElementsByClass, it isn?t. So rather than pulling the function straight out of the book, I?ll leave that up to you to buy it yourself. Instead I?ve pulled this simple method from public domain:

insertAfter() on public domain

function insertAfter(parent, node, referenceNode) {
	parent.insertBefore(node, referenceNode.nextSibling);
}

inArray()

This too is very sad that this isn?t part of the DOM core functionality. But hey, it makes for fun references like this! This function however isn?t quite a function; it?s a prototype that extends the DOM Array object. I remember one day thinking to myself ?surely I can do this in PHP, it?s gotta be in JavaScript.? Well, this extension makes it work just like you?d expect if you?re a PHP developer. Here is a version from EmbiMEDIA

inArray Prototype Array object by EmbiMedia

Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};

3, 2, & 1) getCookie(), setCookie(), deleteCookie()

I honestly don?t know what I would do without these guys. I hate the DOM implementations of setting cookies in JavaScript. In PHP it?s so easy, and it?s easy for one main reason, they work just like the functions below. All three of these functions were found to be public domain and free to use.

getCookie(), setCookie(), deleteCookie() open domain

function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+'='+escape( value ) +
		( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
		( ( path ) ? ';path=' + path : '' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) +
			';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

Last but not least, a bonus function: The Prototype Dollar Function

This function straight up kicks so much ass. First of all, just look at it.

Prototype function $

 
    function $() { var elements = new Array(); 
    for (var i = 0; i < arguments.length;
   i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element);
   if (arguments.length == 1) 
   return element; elements.push(element); }
    return elements;
   } // Sample Usage: var obj1 = document.getElementById('element1'); 
   var obj2 = document.getElementById('element2');
     function alertElements() { var i; 
   var elements = $('a','b','c',obj1,obj2,'d','e');
  for ( i=0;i<"ELEMENTS.LENGTH";I++ )
 { alert(elements[i].id); } }                     
                        

Tell me that?s not beautiful! Short not only by name, but by reference. It not only takes in strings, it takes objects too. You can pass it one argument, or pass it many! This by far is my favorite function of all time which will provide years and years of handiness.

The JavaScript object model is a simple one. The bulk of these objects deal with window content -- documents, links, forms, and so forth. In addition to window-content objects, JavaScript supports a small handful of "built-in" objects. These built-in objects are available regardless of window content and operate independently of whatever page Netscape has loaded.

The built-in objects are Date, Math, String, Array, and Object. Each is used in a unique and not-quite-consistent way. Furthermore, newer versions of JavaScript (as found in Netscape "Atlas," currently in beta) implement several of these objects in a different manner than in Netscape 2.0. In this column we will address these built-in objects and how to use them. And we'll make note of the quirks you'll encounter as you apply these objects to your JavaScript pages.

Understanding the string objectOf all JavaScript's objects, the String object is the most commonly used. In the Netscape 2.0 JavaScript implementation, new string objects are created implicitly using a variable assignment. For example,

var myString = "This is a string";

creates a string, with the specified text, called myString. In Netscape 2.0, there is no actual object called string, and attempting to instantiate a new String object using the new statement results in an error, as String (or string) is not a defined keyword. In the Atlas version of Netscape, however, String is a bona fide object, and the String keyword can be used to create new strings. The following two approaches are allowed in Atlas, but not in Netscape 2.0.

var myString = new String();
myString = "This is a string";

and

var myString = new String ("This is a string");

String objects have one property: length. The length property returns the length of the string and uses the syntax string.length, where string is the name of the string variable. Both of the following display 16.

alert ("This is a string".length)

and

var myString = "This is a string";
alert (myString.length);

While there may be just one string property, JavaScript supports a large number of methods that can be used with strings. These methods can be roughly divided into two broad camps: string management and text format.

String management methods include substring, indexOf, lastIndexOf, and toLowerCase. These are used to return or change the content of the string in some way. For instance, the substring method returns a specified portion of a string. The indexOf method determines the location of a character or group of characters in a string. And the toLowerCase method converts the string to lower case. (As you can imagine, there's also a toUpperCase method.)

Text format methods are used to format text in a document in some special way, and are provided as alternatives to using HTML tags for the same purpose. These methods include big, small, sup, sub, anchor, link, and blink.

String methods can be used directly on strings, or on variables that contain strings. Methods always use open and closed parentheses, even if the method doesn't use parameters. For instance, to convert text to upper case, you'd use one of the following:

var tempVar = "this text is now upper case".toUpperCase();

or

var myString = "this text is now upper case";

var tempVar = myString.toUpperCase();

In Netscape 2.0 there is only one String object, and all strings are created from it. Conversely, strings are first-class objects in Atlas, and each new string is a treated as a separate object. The single-object behavior of strings in Netscape 2.0 can cause some subtle side effects. Take the short script segment that follows. Two strings are created: string1 and string2. A new property (called extra) is assigned to string1. Yet the alert message shows that the property also now belongs to string2.

<SCRIPT>
string1 = "this is string 1"
string2 = "this is string 2"
string1.extra = "new property"
alert (string2.extra)

</SCRIPT>

Technically speaking, strings are "immutable" in JavaScript. That is, the content of the string is static, and cannot be changed. In Netscape 2.0, JavaScript is capable of modifying a string only by creating a new location in memory for it. Because of this, a script that modifies a string many times is prone to memory errors. Each time the string is altered, JavaScript creates a new location in memory for the new version. New strings are created before garbage collection takes place to destroy the old string. Eventually, JavaScript uses all of its available memory, and an "out of memory" error occurs.

A classic example of this problem can be seen in the popular JavaScript "message scrollers," where a message scrolls in the status bar or a text box. For each pass, the scroller redefines the string variable that is displayed. Memory is eventually depleted because JavaScript creates new instances of the string with each pass. For example, the following script will eventually (sooner on some platforms, such as Windows 3.1) cause an "out of memory" error:

<SCRIPT>
var count = 0;
var text = "This is a test of a JavaScript scroller. ";scroll(); function  scroll () {

	var myString = text.substring (count, text.length) + text.substring (0, count)

	window.status = myString

	if (count < text.length)

		count ++;

	else

		count = 0;

	setTimeout ("scroll()", 333);

 	// 333ms is the minimum delay for Netscape 2.0
}
</SCRIPT>

A simple rewrite avoids the problem of creating new blocks of memory. Delete the myString variable assignment, and parse the text directly to the status bar, using window.status. See the revised JavaScript scroller to view the script in action. (Watch the status bar to see the text scroll by.)

window.status = text.substring (count, text.length) + text.substring (0, Count)

(While the above approach avoids JavaScript's string-object replication problem, memory leaks still occur because of the use of the setTimeout method. Over many iterations -- typically several thousand or more -- setTimeout will consume all available memory, and eventually JavaScript will display an "out of memory" message.)

For your reference, here are the methods and properties used with JavaScript's string object:

String Properties

length The length of a string

String Methods

anchor Creates a named anchor (hypertext target)
big Sets text to big
blink Sets text to blinking
bold Sets text to bold
charAt Returns the character at a specified position
fixed Sets text in fixed-pitch font
fontcolor Sets the font color
fontsize Sets font size
indexOf Returns the first occurrence of character x starting from position y
italics Sets text to italics
lastIndexOf Returns the last occurrence of character x starting from position y
link Creates a hyperlink
small Sets text to small
strike Sets text to strikeout
sub Sets text to subscript
substring Returns a portion of a string
sup Sets text to superscript
toLowerString Converts a string to lowercase
toUpperString Converts a string to uppercase

Using JavaScript as a Scientific Calculator

JavaScript's Math object provides advanced arithmetic and trigonometric functions, expanding on JavaScript's basic arithmetic operators (plus, minus, multiply, divide). The Math object in JavaScript is borrowed from Java. In fact, the implementation of the Math object in JavaScript closely parallels the Math class in Java, except that the JavaScript Math object offers fewer methods.

JavaScript's Math object properties are treated as constants. In fact, the property names are in all upper-case, following the usual convention of capitalizing variable constants. These properties return often-used values, including <em>pi</em> and the square root of 2. The Math methods are used in mathematical and trigonometric calculations. Handy Math-object methods include ceil, floor, pow, exp (exponent), max, min, round, and random. (Random is only available when using the X Window platform, however.)

The Math object is static, so you don't need to create a new Math object in order to use it. To access the properties and method of the Math object, you merely specify the Math object, along with the method or property you wish. For example, to return the value of <em>pi</em>, you use:

var pi = Math.PI;

Similarly, to use a math method you provide the name of the method, along with the parameters you wish to use. For example, to round the value of <em>pi</em>, you'd use:

var pi = Math.PI;
                            var pieAreRound = Math.round(pi);	// displays 3

Note that you must specify the Math object by name for each Math method/property you wish to use. JavaScript does not recognize the keywords PI and round all by themselves. Exception: you may use the with statement to associate the names of methods and properties with the Math object. This technique is a handy space-saver when you must use several Math properties and methods. The previous example can be written as

with (Math) {
	var pi = PI;
var pieAreRound = round(pi);
alert (pieAreRound) }

For your reference, here are the properties and methods supported by JavaScript's Math object.

Math Properties

E Euler's constant
LN2 The natural logarithm of 2
LN10 The natural logarithm of 10
LOG2E The base 2 logarithm of e
LOG10E The base 10 logarithm of e
Pi</td> The numeric equivalent of PI: 3.14 etc.
SQRT1_2 The square root of one-half
SQRT2 The square root of 2

Math Methods

abs Returns the absolute value of a number
acos Returns the arc cosine of a number
asin Returns the arc sine of a number
atan Returns the arc tangent of a number
ceil Returns the least integer greater than or equal to a number
cos Returns the cosine of a number
exp Returns e (Euler's constant) to the power of a number
floor Returns the greatest integer less than or equal to its argument
log Returns the natural logarithm (base e) of a number
max Returns the greater of two values
min Returns the lesser of two values
pow Returns the value of a number times a specified power
random Returns a random number (X-platforms only)
round Returns a number rounded to the nearest whole value
sin Returns the sine of a number
sqrt Returns the square root of a number
tan Returns the tangent of a number

Asking JavaScript for a Date Also borrowed by Java is the Date object, which can be used in JavaScript to determine the current time and date. A popular JavaScript application of the Date object is displaying a digital clock in a text box. The script uses the Date object to update the clock once every second. You also use the Date object to perform date math. For example, your script might determine the number of days between now and a certain future date. You can use this to display a "countdown," such as the number of days left of your company's big sale.

JavaScript treats the Date object like a constructor class. To use Date you must create a new Date object; you can then apply the various Date methods to get and set dates. (The Date object has no properties.) If you're familiar with the Date class in Java, you'll find the properties of the JavaScript Date object largely the same. The most commonly used methods are the get methods, which obtain the time and date of the value in the Date object. These methods are:

  • getHours() - Returns the hour
  • getMinutes() - Returns the minutes
  • getSeconds() - Returns the seconds
  • getYear() - Returns the year ("96" is 1996)
  • getMonth() - Returns the month ("0" is January)
  • getDate() - Returns the day of the month
  • getDay() - Returns the day of the week ("0" is Sunday)

(JavaScript's Date object also provides for setting the time and date of the Date object, but these are seldom used.)

Constructing a new Date object can take several forms. To return an object containing the current date and time, you use the Date object without parameters. In the following, date_obj is a new object, containing the value of the current date and time, as set by the computer's system clock.

var date_obj = new Date();

Alternatively, you can specify a given date and time as part of the date constructor. Either of these methods is allowed -- both set the new date object to January 1, 1997, at midnight local time.

var date_obj = new Date ("January 1 1997 00:00:00")

and

var date_obj = new Date (97, 0, 1, 12, 0, 0)

To use a Date method, append the method to the date object you previously created. For example, to return the current year, use:

var now = new Date();

var yearNow = now.getYear();

For your reference, here are the methods supported by JavaScript's Date object.

Date Methods

getDate Returns the day of month of a specified date
getDay Returns the day of week of a specified date
getHours Returns the hour of a specified date
getMinutes Returns the minutes of a specified date
getMonth Returns the month of a specified date
getSeconds Returns the seconds of a specified date
getTime Returns the number of seconds between January 1, 1970 and specified date
getTimeZoneoffset Returns the time zone offset in minutes for the current locale
getYear Returns the year of specified date
parse Returns the number of milliseconds in a data since January 1, 1970, 00:00:00
setDate Sets the date
setHours Sets the hours of a specified date
setMinutes Sets the minutes of a specified date
setMonth Sets the month of a specified date
setSeconds Sets the seconds of a specified date
setTime Sets the time of a specified date
setYear Sets the year of a specified date
toGMTString Converts a date to a string using GMT conventions
toLocaleString Converts a date to a string using locale conventions
toString Converts the value of a Date object or current location object to a string
UTC Converts a comma-delimited date to the number of seconds since Jan 1, 1970

Date GotchasWhile the Date object is fairly straightforward to use, it does suffer some bugs, including a few that will cause Netscape to crash. Keep the following in mind when working with dates.

Macintosh is one day in the futureIn the Macintosh version of Netscape 2.0, the Date object is off by one day in the future. You can compensate for this by subtracting a day, using a technique such as

now.setDate(now.getDate()-1);

You must be careful that you subtract the day for Macintosh users only, and only if they are using Netscape 2.0. (This bug is gone in Atlas.) You can use the navigator.userAgent property for this, but an easier approach is

var testForMac = new Date(0);	// start of JavaScript epoch: Jan 1, 1970

if (testForMac == 86400000)

	now.setDate(now.getDate()-1);

Dates before 1970 can crash NetscapeA natty bug in most platforms of Netscape 2.0 -- and in the beta versions of Atlas -- causes an unceremonious crash if you attempt you use a date prior to January 1, 1970. You can avoid the bug if you remember to always specify dates of 1970 and beyond. The issue isn't so easily dismissed if you allow user entry of dates. At the very least, if you allow the user to type the year as text, you will need to first verify that the year is 1970 or beyond. This can be done with a simple if expression (in the following, the userDate variable contains the year typed by the user):

if (parseInt(userDate) < 1970)

	// invalid year

else

	// valid year

Specify numeric values for dates after 1999Similar to the pre-1970 date bug, Netscape can crash if you provide a string value for any date beyond 1999. However, no crash results if you use numeric values for the date, instead of a string. For example, the first line below causes a crash, but the second one does not:

date_obj = new Date ("January 1, 2000"); 	// crashes Netscape

date_obj = new Date ("100, 0, 1"); 		// does not crash Netscape

Creating Objects and Arrays JavaScript supports two (currently) undocumented object constructors: Array and Object. Both do a similar job, but are used in different situations. In JavaScript, an array is really just an object, using numbers or associative names for the array elements. You can create new arrays and objects with either constructor, but for readability, you'll probably want to use the constructor that is most closely associated with your application. Use Array when creating an array; use Object when creating an object.

Let's tackle the Array constructor first.

In JavaScript you can create an array explicitly using your own constructor function. Here is an example of a basic array constructor.

function makeArray(numElements) {
   this.length = numElements
   for (count = 1; count <= numElements; count++) 
      this[count] = 0;
   return (this);
}

To define a new array, you call the makeArray function using the new statement. The following example creates an array with three elements, and fills them with data.

var myArray = new makeArray(3);
myArray[1] = "item 1";
myArray[2] = "item 2";
myArray[3] = "item 3";

Actually, JavaScript doesn't much care how you make your arrays. Though you can define the number of elements in the array, the makeArray function uses this value only to pre-load an initial value in the first three elements. (Element 0 contains the length of the array; element[0] is synonymous with the length property.) You can add additional elements at any time, even after the array has been created.

The Array object in JavaScript does the same work as the makeArray constructor function. You can use it to create a new array, then provide the data for each element in the usual manner. In Netscape 2.0, the Array object ignores any "length" or number of elements value you pass to it, so if you need to store the number of elements in the array, you must do so explicitly.

var myArray = new Array();
myArray[0] = 3;
myArray[1] = "item 1";
myArray[2] = "item 2";
myArray[3] = "item 3";

When the array is created, JavaScript merely creates an object for it, but doesn't fill any of the elements with an initial value. JavaScript returns null when you access an element of an array that has not been expressly defined. In the example above myArray[4] returns null, since element[4] is not defined.

In Atlas, the Array object accepts a length parameter, so you don't need to set the length separately. Merely pass the number of elements as a parameter of the Array() constructor; you may then refer to the length using the construct array_name.length. You can remove array elements by defining them with null, but the length property remains constant. You can, however, manually change the length property at any time yourself, simply by defining a new value for array_name.length. As in Netscape 2.0, undefined array elements contain a null value.

Object is a generic object constructor, and is borrowed from Java. However, JavaScript's Object is a much simplified version of the Java Object class. In Java, Object is used as a superclass, but in JavaScript, Object is used as a simplified means of creating new objects without providing an object constructor function. In JavaScript, an object constructor function is called with the new statement, and the function defines any properties or methods of the object. In the following simplified example, the calling statement instantiates a new object named myObject. The makeObject function creates the object, defining one property ("name") to it.

myObject = new makeObject ("my object");
function makeObject(name) {
	this.name = name;
	return (this);
}

The Object constructor saves you the trouble of making a constructor function, and is handy when you don't need or want to define methods and properties of the object when it is created, or when you want to define just one two properties. These following two lines replicate the example above:

myObject = new Object();
myObject.name = "my object";

You might use the Object constructor as a quick means to create an object. One such example is a color database, which uses JavaScript as a miniature database. The database can consist of just one or two objects; separate properties of the objects contain the individual data items.

The following script uses JavaScript to built a small database lookup application. The Object constructor creates two objects: an index object and a data object. The index object is really an array with 10 elements; each element contains the name of a Netscape-supported color. The data object mirrors the sequence of the color names, and includes the equivalent hexadecimal value for that color -- the color aliceblue is f0f8ff, for example, and blanchedalmond is ffebcd. Note that the same database can be constructed using Array.

<HTML><HEAD>
<TITLE>Color Database</TITLE>
<SCRIPT LANGUAGE="JavaScript">
Idx = new Object();
Data = new Object();
Idx[0]=10
Idx[1]="aliceblue"
Idx[2]="antiquewhite"
Idx[3]="aqua"
Idx[4]="aquamarine"
Idx[5]="azure"
Idx[6]="beige"
Idx[7]="bisque"
Idx[8]="black"
Idx[9]="blanchedalmond"
Idx[10]="blue"
Data[1]="f0f8ff"
Data[2]="faebd7"
Data[3]="00ffff"
Data[4]="7fffd4"
Data[5]="f0ffff"
Data[6]="f5f5dc"
Data[7]="ffe4c4"
Data[8]="000000"
Data[9]="ffebcd"
Data[10]="0000ff"
function checkDatabase() {
	var Found = false;
	var Item = document.testform.color.value.toLowerCase();
	for (Count = 1; Count <= Idx[0]; Count++) {
		if (Item == Idx[Count]) {
			Found = true;
			alert ("The hex triplet for '" + Item + "' is #" + Data[Count]);
			break;	}
	}
	if (! Found)
alert ("Sorry, the color '" + Item +"' is not listed in the database.");
}
</SCRIPT>
<FORM NAME="testform" onSubmit="checkDatabase()">
Specify a color name, then click the "Find" button to see its hex triplet: <BR> 
<INPUT TYPE="text" NAME="color" Value="" onClick=0> <P>
<INPUT TYPE="button" NAME="button" Value="Find" onClick="checkDatabase()"> 
</FORM>
</BODY></HTML>

JavaScript's associative arrays can come in handy when creating databases. Associative array names are synonymous with the object's property names. With this feature you can simplify the color database script by defining a single object -- named Idx -- for the colors. Then use the names of the colors as the property names, defined as Idx["colorname"]. Each property is assigned the equivalent hexadecimal color value. For example, the property Idx["aliceblue"] -- which is the functional equivalent to the syntax Idx.aliceblue -- is assigned the hex value f0f8ff.

In the revised color database example, the user types a color name, which doubles as a property name for the Idx object. An if expression determines whether the Idx object contains a property with that name. If the return value is "<undefined>" then no such property exists, and therefore the color is not listed in the database. If the value is something else, it is assumed to be the hex value of the specified color, and that value is displayed in an alert box.

<HTML>

<HEAD>

<TITLE>Another Color Database</TITLE>
<SCRIPT LANGUAGE="JavaScript">
Idx = new Object();
Idx["aliceblue"] = "f0f8ff"
Idx["antiquewhite"] ="faebd7"
Idx["aqua"] ="00ffff"
Idx["aquamarine"] ="7fffd4"
Idx["azure"] ="f0ffff"
Idx["beige"] ="f5f5dc"
Idx["bisque"] ="ffe4c4"
Idx["black"] ="000000"
Idx["blanchedalmond"] ="ffebcd"
Idx["blue"] ="0000ff"
function checkDatabase() {
	var Item = document.testform.color.value.toLowerCase();
	if ("" + Idx[Item] == "<undefined>")

		alert ("Sorry, the color '" + Item +"' is not listed in the database.");
	else
		alert (Idx[Item])
} </SCRIPT> <FORM NAME="testform" onSubmit="checkDatabase()"> Specify a color name, then click the "Find" button to see its hex triplet: <BR> <INPUT TYPE="text" NAME="color" Value="" onClick=0> <P> <INPUT TYPE="button" NAME="button" Value="Find" onClick="checkDatabase()"> </FORM>/BODY>
</HTML>

Change Font Color JavaScript

<HTML><HEAD><TITLE>Change Font Color</TITLE>
<META http-equiv=Content-Type content="text/html; charset=utf-8">
<SCRIPT>
function changeColor()
{
  document.getElementById("color1").style.color="#FF0000";
  document.getElementById("color2").style.color="#FFFF00";
  document.getElementById("color3").style.color="#339933";
  document.getElementById("color4").style.color="#0000FF";
  document.getElementById("color5").style.color="#FF6600";
}

function defaultColor()
{
  document.getElementById("color1").style.color="";
  document.getElementById("color2").style.color="";
  document.getElementById("color3").style.color="";
  document.getElementById("color4").style.color="";
  document.getElementById("color5").style.color="";
}
</SCRIPT>

<META content="MSHTML 6.00.6000.16825" name=GENERATOR></HEAD>
<BODY>
<SPAN id=color1>Red color</SPAN><BR><SPAN id=color2>yellow color</SPAN><BR><SPAN id=color3>green color</SPAN><BR><SPAN id=color4>blue color</SPAN>
<SPAN id=color5>orange color</SPAN><BR><BR><A href="javascript:changeColor()">Change Font Color JavaScript</A><BR><BR><A href="javascript:defaultColor()">Change default Font Color JavaScript</A> </BODY></HTML>

Ajax is only a name given to a set of tools that were previously existing.
The main part is XMLHttpRequest, a class usable in JavaScript , that was implemented into Internet Explorer since the 4.0 version.
The same concept was named XMLHTTP some times, before the Ajax name becomes commonly used.
The use of XMLHttpRequest in 2005 by Google, in Gmail and GoogleMaps has contributed to the success of this format. But this is the name Ajax itself that made the technology so popular.

Why to use Ajax?

Mainly to build a fast, dynamic website, but also to save resources.
For improving sharing of resources, it is better to use the power of all the client computers rather than just an unique server and network. Ajax allows to perform processing on client computer (in JavaScript) with data taken from the server.
The processing of web page formerly was only server-side, using web services or PHP scripts, before the whole page was sent within the network.
But Ajax can selectively modify a part of a page displayed by the browser, and update it without the need to reload the whole document with all images, menus, etc...
For example, fields of forms, choices of user, may be processed and the result displayed immediately into the same page.

What is Ajax in depth?

Ajax is a set of technologies, supported by a web browser, including these elements:

  • HTML and CSS for presenting.
  • JavaScript (ECMAScript) for local processing, and DOM (Document Object Model) to access data inside the page or to access elements of XML file read on the server (with the getElementByTagName method for example)...
  • The XMLHttpRequest class read or send data on the server asynchronously.
optionally...
  • The DomParser class may be used
  • PHP or another scripting language may be used on the server.
  • XML and XSLT to process the data if returned in XML form.
  • SOAP may be used to dialog with the server.

The "Asynchronous" word, means that the response of the server while be processed when available, without to wait and to freeze the display of the page.

How does it works?

Ajax uses a programming model with display and events. These events are user actions, they call functions associated to elements of the web page.
Interactivity is achieved with forms and buttons. DOM allows to link elements of the page with actions and also to extract data from XML files provided by the server.
To get data on the server, XMLHttpRequest provides two methods:
- open: create a connection.
- send: send a request to the server.
Data furnished by the server will be found in the attributes of the XMLHttpRequest object:
- responseXml   for an XML file or
- responseText   for a plain text.

Take note that a new XMLHttpRequest object has to be created for each new file to load.

We have to wait for the data to be available to process it, and in this purpose, the state of availability of data is given by the readyState attribute of XMLHttpRequest.

States of readyState follow (only the last one is really useful):
0: not initialized.
1: connection established.
2: request received.
3: answer in process.
4: finished.

Ajax and DHTML

DHTML has same purpose and is also, as Ajax, a set of standards:
- HTML,
- CSS,
- JavaScript.
DHTML allows to change the display of the page from user commands or from text typed by the user.
Ajax allows also to send requests asynchronously and load data from the server.

The XMLHttpRequest class

Allows to interact with the servers, thanks to its methods and attributes.

Attributes

readyState the code successively changes value from 0 to 4 that means for "ready".
status 200 is OK
404 if the page is not found.
responseText holds loaded data as a string of characters.
responseXml holds an XML loaded file, DOM's method allows to extract data.
onreadystatechange property that takes a function as value that is invoked when the readystatechange event is dispatched.

Methods

open(mode, url, boolean) mode: type of request, GET or POST
url: the location of the file, with a path.
boolean: true (asynchronous) / false (synchronous).
optionally, a login and a password may be added to arguments.
send("string") null for a GET command.

Building a request, step by step

First step: create an instance

This is just a classical instance of class, but two options must be tried, for browser compatibility.

if (window.XMLHttpRequest)    // Object of the current
    windows
{ 
    xhr = new XMLHttpRequest();     // Firefox, Safari,
        ...
} 
else 
 if (window.ActiveXObject)   // ActiveX version
 {
    xhr = new ActiveXObject("Microsoft.XMLHTTP");  // Internet Explorer
   
 } 

or exceptions may be used instead:

try {
   xhr = new ActiveXObject("Microsoft.XMLHTTP");   // Trying Internet
       Explorer
}
catch(e)    // Failed 
{
  xhr = new XMLHttpRequest()
}

Second step: wait for the response

The response and further processing are included in a function and the return of the function will be assigned to the onreadystatechange attribute of the object previously created.

xhr.onreadystatechange = function() { // instructions to process the response }; <
    
if (xhr.readyState == 4)
{
 // Received, OK
} else 
{
  // Wait...
}

Third step: make the request itself

Two methods of XMLHttpRequest are used:
- open: command GET or POST, URL of the document, true for asynchronous.
- send: with POST only, the data to send to the server.
The request below read a document on the server.

xhr.open('GET', 'http://www.xul.fr/somefile.xml', true);                  
xhr.send(null); 

Examples

Get a text

<html>
<head>
<script>
function submitForm()
{ 
    var xhr; 
    try { xhr = new XMLHttpRequest(); }                 
    catch(e) 
    {    
      xhr = new ActiveXObject(Microsoft.XMLHTTP);
    } 
 
    xhr.onreadystatechange  = function()
    { 
         if(xhr.readyState  == 4)
         {
              if(xhr.status  == 200) 
                  document.ajax.dyn="Received:"  + xhr.responseText; 
              else 
                 document.ajax.dyn="Error code " + xhr.status;
         }
    }; 

   xhr.open(GET, "data.txt",  true); 
   xhr.send(null); 
} 
</script>
</head>
                 
<body>
    <FORM method="POST" name="ajax" action="">                  
         <INPUT type="BUTTON" value="Submit"  ONCLICK="submitForm()">
         <INPUT type="text" name="dyn"  value=""> 
    </FORM>
 </body>
 </html> 

More Info about above code 

new ActiveXObject(Microsoft.XMLHTTP)
   This constructor is for Internet Explorer.

new XMLHttpRequest()
   This constructor is for any other browser including Firefox.

http.onreadystatechange

  An anonymous function is assigned to the event indicator.

http.readyState == 4
   The 4 state means for the response is ready and sent by the server.

http.status == 200
   This status means ok, otherwise some error code is returned, 404 for example.

http.open( "POST", "data.xml", true);
   POST or GET
   URL of the script to execute.
   true for asynchronous (false for synchronous).

http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
   This is for POST only.

http.send(document.getElementById("TYPEDTEXT").value);
   Send data to the server. Data comes from the "TYPEDTEXT" variable filled throught the form by the user.

Get from XML

To get data from an XML file we have just to replace this line:

document.ajax.dyn="Received:" + xhr.responseText; 

by this code:

var doc = xhr.responseXML;   // Assign the XML file to a
    var
var element = doc.getElementsByTagName('root').item(0);  
    // Read the first element
document.ajax.dyn.value= element.firstChild.data;    //
    Assign the content to the form

Write to body

here, the text read is put into the body of the page, and not into a textfield. The code below replaces the textfield form object and the second part replaces the assignment into the JavaScript function.

<div id="zone">
     ... some text to replace ...
 </div> 
document.getElementById("zone").innerHTML = "Received:" + xhr.responseText;	               

Post a text

here a text is sent to the server and is written into a file. The call to the "open" method changes, the argument is POST, the url is the name of a file or script that receives the data sent, and that must process it. And the "send" method has now a value as argument that is a string of parameters.

xhr.open("POST", "ajax-post-text.php", true); 
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");                  
xhr.send(data);

The parameter of the send method is in format of the HTML POST method. When several values are sent, they are separated by the ampersand symbol:

var data = "file=" + url + "&content=" + content;
The "file" parameter is the name of a file created to store the content. The filename must be checked by the server to prevent any other file to be modified.

Using an external file

It is simpler to include a JavaScript file. This line will be included into the head section of the HTML page:

<script src="ajax.js" type="text/javascript"></script>

And the function is called with this statement:

var xhr = createXHR();

How to build an Ajax website?

You need for some wrapper. A short list of frameworks is provided below.
Your JavaScript program, integrated into a web page, sends request to the server to load files for rebuilding of pages. The received documents are processed with Dom's methods or XML parsers and the data are used to update the pages.

Drawbacks of Ajax

- If JavaScript is not activated, Ajax can't works. The user must be asked to set JavaScript from within options of the browser, with the "noscript" tag.
- Since data to display are loaded dynamically, they are not part of the page, and the keywords inside are not used by search engines.
- The asynchronous mode may change the page with delays (when the processing on the server take some times), this may be disturbing.
- The back button may be deactivated (this is not the case in examples provided here). This may be overcomed.

AJAX/Javascript XML Tips & Tricks

Here are some XML processing examples in Javascript. If you've got some XML data with XMLHttpRequest (there is actually no XMLHttpRequest in the examples - we create the XML object from a string - can be handy too) you need to read/convert etc. it to some other format and do something with it. Traversing a DOM/XML tree can be tricky, so have a look at these examples:


Example #1:
Using getElementsByTagName, we iterate thru the XML tree and read the numerous children/sibling.

<html>
<body>
<script>
var xmlstring = '<?xml version=\"1.0\"?>\
<shoppingcart date="14-10-2005" total="123.45">\
	<item code="12345">\
		<name>Widget</name>\
		<quantity>1</quantity>\
	</item>\
	<item code="54321">\
		<name>Another Widget</name>\
		<quantity>2</quantity>\
	</item>\
</shoppingcart>';

// convert the string to an XML object
var xmlobject = (new DOMParser()).parseFromString(xmlstring, "text/xml");
// get the XML root item
var root = xmlobject.getElementsByTagName('shoppingcart')[0];
var date = root.getAttribute("date");
alert("shoppingcart date=" + date);

var items = root.getElementsByTagName("item");
for (var i = 0 ; i < items.length ; i++) {
	// get one item after another
	var item = items[i];
	// now we have the item object, time to get the contents
	// get the name of the item
	var name = item.getElementsByTagName("name")[0].firstChild.nodeValue;
	// get the quantity
	var quantity = item.getElementsByTagName("quantity")[0].firstChild.nodeValue;
	alert("item #" + i + ": name=" + name + " quantity=" + quantity);
}
</script>
</body>
</html>

Example #2:
Here is a more universal example with the method "childNodes".

<html>
<body>
<script>
var xmlstring = '<?xml version="1.0"?>\
<root>\
	<data>\
		<row>\
			<cell>Admiral</cell>\
			<cell>Melon</cell>\
			<cell>Carrot</cell>\
		</row>\
		<row>\
			<cell>Captain</cell>\
			<cell>Banana</cell>\
			<cell>Zucchini</cell>\
		</row>\
	</data>\
	<data>\
		<row>\
			<cell>Midshipman</cell>\
			<cell>Orange</cell>\
			<cell>Potatoe</cell>\
		</row>\
	</data>\
</root>';

// convert the string to an XML object
var xmlobject = (new DOMParser()).parseFromString(xmlstring, "text/xml");
// get the XML root item
var root = xmlobject.getElementsByTagName('root')[0];
           
for (var iNode = 0; iNode < root.childNodes.length; iNode++) {
   var node = root.childNodes.item(iNode);
   for (i = 0; i < node.childNodes.length; i++) {
      var sibling = node.childNodes.item(i);
      for (x = 0; x < sibling.childNodes.length; x++) {
         var sibling2 = sibling.childNodes.item(x);
         if (sibling2.childNodes.length > 0) {
            var sibling3 = sibling2.childNodes.item(0);
            alert(sibling3.data);
         }
      }
   }
}
</script>
</body>
</html>

Javascript Best Practices

Introduction

This document is a list of best practices and preferred ways of developing javascript code, based on opinions and experience from many developers in the javascript community. Since this is a list of recommendations rather than a list of absolute rules, experienced developers may have slightly differing opinions from those expressed below.

Always Use 'var'

Variables in javascript either have global scope or function scope, and using the 'var' keyword is vital to keeping them straight. When declaring a variable for use either as a global variable or as a function-level variable, always prefix the declaration with the 'var' keyword. The example below highlights the potential problem caused by not doing so.

Problem Caused By Not Using Var
var i=0; // This is good - creates a global variable
function test() {
   for (i=0; i<10; i++) {
      alert("Hello World!");
   }
}
test();
alert(i); // The global variable i is now 10!

Since the variable i inside the function was not declared as a function-level variable by using the 'var' keyword, it references the global variable in this example. It is a good idea to always declare global variables using 'var', but it is vital to declare function-scoped variables using 'var'. The two approaches below are functionally identical.

Fixed Function
function test() {
   var i=0;
   for (i=0; i<10; i++) {
      alert("Hello World!");
   }
}
Fixed Function
function test() {
   for (var i=0; i<10; i++) {
      alert("Hello World!");
   }
}

Feature-Detect Rather Than Browser-Detect

Some code is written to detect browser versions and to take different action based on the user agent being used. This, in general, is a very bad practice. Any code which even looks at the global "navigator" object is suspect.

The better approach is to use feature detection. That is, before using any advanced feature that an older browser may not support, check to see if the function or property exists first, then use it. This is better than detecting the browser version specifically, and assuming that you know its capabilities. An in-depth article about this topic can be found at http://www.jibbering.com/faq/faq_notes/not_browser_detect.html.

Example
if (document.getElementById) {
   var element = document.getElementById('MyId');
}
else {
   alert('Your browser lacks the capabilities required to run this script!');
}

Use Square Bracket Notation

When accessing object properties that are determined at run-time or which contain characters not compatible with dot notation, use square bracket notation. If you are not an experienced javascript programmer, it's not a bad practice to use square bracket notation all the time.

Objects properties in javascript can be accessed primarily in two ways: Dot notation and Square bracket notation.

Dot notation
MyObject.property
Square bracket notation
MyObject["property"]

With dot notation, the property name is hard-coded and cannot be changed at run-time. With bracket notation, the property name is a string which is evaluated to resolve the property name. The string can be hard-coded, or a variable, or even a function call which returns a string property name.

If a property name is being generated at run-time, the bracket notation is required. For example, if you have properties "value1", "value2", and "value3", and want to access the property using a variable i=2:

This Will Work
MyObject["value"+i]
This Will Not
MyObject.value+i

Also, in some server-side environments (PHP, Struts, etc) form field names are appended with [] to denote that the form field should be treated as an array on the server-side. However, referencing a field name containing [] using dot notation will not work because [] is the syntax for reference a javascript array. So, square bracket notation is required.

This Will Work
formref.elements["name[]"]
This Will Not
formref.elements.name[]

The recommendation for using square bracket notation is to always use it when it is required (obviously). Using it when not strictly required is a matter of personal preference and convention. One good rule of thumb is to use dot notation to access standard properties of objects, and square bracket notation to access properties which are defined as objects in the page. So, while document["getElementById"]() is perfectly vaid using square bracket notation, document.getElementById() is the preferred syntax because getElementById is a standard property of the document object as defined in the DOM specifications. Mixing the use of dot and square bracket notation makes it clear which properties are standard and which are names defined by the content:

document.forms["myformname"].elements["myinput"].value

Here, the forms property is a standard property of document, while the form name myformname is defined by the page content. Likewise, the elements property and value property are both defined by the specs, but then myinput name is defined in the page. This syntax is very clear and easy to understand and is a recommended convention to follow, but not a strict rule.

Avoid 'eval'

The eval() function in javascript is a way to run arbitrary code at run-time. In almost all cases, eval should never be used. If it exists in your page, there is almost always a more correct way to accomplish what you are doing. For example, eval is often used by programmers who do not know about using Square Bracket Notation.

The rule is, "Eval is evil." Don't use it unless you are an experienced developer and know that your case is an exception.

Reference Forms and Form Elements Correctly

All forms in an HTML form should have a name attribute. For XHTML documents, the name attribute is not required and instead the form tag should have an id attribute and should be referenced using document.getElementById(). Referencing forms using indexes, such as document.forms[0] is a bad practice in almost all cases. Some browsers make the form available as a property of the document itself using its name. This is not reliable and shouldn't be used.

The example below uses square bracket notation and correct object references to show the most fool-proof way of referencing a form input.

Correct Reference To Form Input
document.forms["formname"].elements["inputname"]
Bad Practice
document.formname.inputname

If you will be referencing multiple form elements within a function, it's best to make a reference to the form object first and store it in a variable. This avoids multiple lookups to resolve the form object reference.

var formElements = document.forms["mainForm"].elements;
formElements["input1"].value="a";
formElements["input2"].value="b";

When validating an input field using onChange or similar event handlers, it is always a good idea to pass a reference to the input element itself into the function. Every input element within a form has a reference to the form object that it is contained in.

<input type="text" name="address" onChange="validate(this)">

function validate(input_obj) {
   // Get a reference to the form which contains this element
   var theform = input_obj.form;
   // Now you can check other inputs in the same form without
   // hard-coding a reference to the form itself
   if (theform.elements["city"].value=="") {
      alert("Error");
   }
}

By passing a reference to the form element and accessing its form property, you can write a function which does not contain a hard reference to any specific form name on the page. This is a good practice because the function becomes more reusable.

Avoid 'with'

The 'with' statement in javascript inserts an object at the front scope chain, so any property/variable references will first try to be resolved against the object. This is often used as a shortcut to avoid multiple long references.

Example Using with
with (document.forms["mainForm"].elements) {
   input1.value = "junk";
   input2.value = "junk";
}

The problem is that the programmer has no way to verify that input1 or input2 are actually being resolved as properties of the form elements array. It is checked first for properties with these names, but if they aren't found then it continues to search up the scope chain. Eventually, it reaches the global object where it tries to treat "input1" and "input2" as global variables and tries to set their "value" properties, which result in an error.

Instead, create a reference to the reused object and use it to resolve references.

Using A Reference Instead
var elements = document.forms["mainForm"].elements;
elements.input1.value = "junk";
elements.input2.value = "junk";

Use onclick In Anchors Instead Of javascript: Pseudo-Protocol

When you want to trigger javascript code from an anchor <A> tag, the onclick handler should be used rather than the javascript: pseudo-protocol. The javascript code that runs within the onclick handler must return true or false (or an expression than evalues to true or false) back to the tag itself - if it returns true, then the HREF of the anchor will be followed like a normal link. If it returns false, then the HREF will be ignored. This is why "return false;" is often included at the end of the code within an onclick handler.

Correct Syntax
<a href="javascript_required.html" onclick="doSomething(); return false;">go</a>

In this case, the "doSomething()" function (defined by the user somewhere in the page) will be called when the link is clicked, and then false will be returned. The href will never be followed for javascript-enabled browsers. However, if the browser does not have javascript enabled, the javascript_required.html file will be loaded, where you can inform your user that javascript is required. Often, links will just contain href="#" for the sake of simplicity, when you know for sure that your users will have javascript enabled. This practice is discouraged. It's always a good idea to put a local fall-back page that will be loaded for users with javascript disabled.

Sometimes, you want to conditionally follow a link. For example, if a user is navigating away from your form page and you first want to validate that nothing has changed. In this case, your onclick will call a function and it will return a value itself to say whether the link should be followed.

Conditional Link Following
<a href="/" onClick="return validate();">Home</a>

function validate() {
	return prompt("Are you sure you want to exit this page?");
}

In this case, the validate() function should always return either true or false. True if the user should be allowed to navigate back to the home page, or false if the link should not be followed. This example prompts the user for confirmation, then returns true or false, depending on if the user clicked OK or Cancel.

Below are examples of things NOT to do. If you see code like this in your pages, it is not correct and should be fixed.

What Not To Do
<a href="javascript:doSomething()">link</a>
<a href="#" onClick="doSomething()">link</a>
<a href="#" onClick="javascript:doSomething();">link</a>
<a href="#" onClick="javascript:doSomething(); return false;">link</a>

Use The Unary + Operator To TypeConvert To Number

In javascript, the + operator is used for both addition and concatenation. This can cause problems when adding up form field values, for example, since javascript is a non-typed language. Form field values will be treated as strings, and if you + them together, javascript will treat it as concatenation instead of addition.

Problematic Example
<form name="myform" action="[url]">
<input type="text" name="val1" value="1">
<input type="text" name="val2" value="2">
</form>

function total() {
	var theform = document.forms["myform"];
	var total = theform.elements["val1"].value + theform.elements["val2"].value;
	alert(total); // This will alert "12", but what you wanted was 3!
}

To fix this problem, Javascript needs a hint to tell it to treat the values as numbers, rather than strings. You can use the unary + operator to convert the string value into a number. Prefixing a variable or expression with + will force it to evaluate as a number, which can then be successfully used in a math operation.

Fixed Example
function total() {
	var theform = document.forms["myform"];
	var total = (+theform.elements["val1"].value) + (+theform.elements["val2"].value);
	alert(total); // This will alert 3
}

Avoid document.all

document.all was introduced by Microsoft in IE and is not a standard javascript DOM feature. Although many newer browsers do support it to try to support poorly-written scripts that depend on it, many browsers do not.

There is never a reason to use document.all in javascript except as a fall-back case when other methods are not supported and very early IE support (<5.0) is required. You should never use document.all support as a way to determine if the browser is IE, since other browsers also now support it.

Only Use document.all As A Last Resort
if (document.getElementById) {
	var obj = document.getElementById("myId");
}
else if (document.all) {
	var obj = document.all("myId");
}

Some rules for using document.all are

  • Always try other standard methods first
  • Only fall back to using document.all as a last resort
  • Only use it if you need to support IE versions earlier than 5.0
  • Always check that it is supported with "if (document.all) { }" around the block where you use it.

Don't Use HTML Comments In Script Blocks

In the ancient days of javascript (1995), some browsers like Netscape 1.0 didn't have any support or knowledge of the script tag. So when javascript was first released, a technique was needed to hide the code from older browsers so they wouldn't show it as text in the page. The 'hack' was to use HTML comments within the script block to hide the code.

Using HTML Comments In Script Is Bad
<script language="javascript">
<!--
   // code here
//-->
</script>

No browsers in common use today are ignorant of the <script> tag, so hiding of javascript source is no longer necessary. In fact, it can be considered harmful for the following reasons:

  • Within XHTML documents, the source will actually be hidden from all browsers and rendered useless
  • -- is not allowed within HTML comments, so any decrement operations in script are invalid

Avoid Cluttering The Global Namespace

Global variables and functions are rarely required. Using globals may cause naming conflicts between javascript source files and cause code to break. For this reason, it is a good practice to encapsulate functionality within a single global namespace.

There are several ways to accomplish this task, some of which are much more complicated than others. The simplest approach is to create a single global object and assign properties and methods to this object.

Creating A Namespace
var MyLib = {}; // global Object cointainer
MyLib.value = 1;
MyLib.increment = function() { MyLib.value++; }
MyLib.show = function() { alert(MyLib.value); }

MyLib.value=6;
MyLib.increment();
MyLib.show(); // alerts 7

Namespaces can also be created using Closures, and Private Member Variables can also be simulated in javascript.

Avoid sync "Ajax" calls

When making "Ajax" requests, you may choose either async or sync mode. Async mode runs the request in the background while other browser activities can continue to process. Sync mode will wait for the request to return before continuing.

Requests made with sync mode should be avoided. These requests will cause the browser to lock up for the user until the request returns. In cases where the server is busy and the response takes a while, the user's browser (and maybe OS) will not allow anything else to be done. In cases where a response is never properly received, the browser may continue to block until the request is timed out.

If you think that your situation requires sync mode, it is most likely time to re-think your design. Very few (if any) situations actually require Ajax requests in sync mode.

Use JSON

When storing data structures as plain text or sending/retrieving data structures via  Ajax use JSON instead of XML when possible. JSON (JavaScript Object Notation) is a more compact and efficient data format, and is language-neutral.

Use Correct <script> Tags

The LANGUAGE attribute is deprecated in the <script> tag. The proper way to create a javascript code block is:

<script type="text/javascript">
// code here
</script>

I find a lot of this AJAX stuff a bit of a hype. Lots of people have been using similar things long before it became ?AJAX?. And it really isn?t as complicated as a lot of people make it out to be. Here is a simple example from one of my apps. First the Javascript:

function createRequestObject() {
     var ro;
     var browser = navigator.appName;
     if(browser == "Microsoft Internet Explorer"){
          ro = new ActiveXObject("Microsoft.XMLHTTP");
     }else{
          ro = new XMLHttpRequest();
     }
     return ro;
}

var http = createRequestObject();

function sndReq(action) {
     http.open('get', 'rpc.php?action='+action);
     http.onreadystatechange = handleResponse;
     http.send(null);
}

function handleResponse() {
     if(http.readyState == 4){
          var response = http.responseText;
          var update = new Array();

          if(response.indexOf('|') != -1) {
               update = response.split('|');
               document.getElementById(update[0]).innerHTML = update[1];
          }
     }
}

This creates a request object along with a send request and handle response function. So to actually use it, you could include this js in your page. Then to make one of these backend requests you would tie it to something. Like an onclick event or a straight href like this:

<a xhref="javascript:sndReq('foo')" mce_href="javascript:sndReq('foo')">[foo]</a>

That means that when someone clicks on that link what actually happens is that a backend request to rpc.php?action=foo will be sent.

In rpc.php you might have something like this:

switch($_REQUEST['action']) {
     case 'foo':
          /* do something */
          echo "foo|foo done";
          break;
     ...
}

Now, look at handleResponse. It parses the ?foo|foo done? string and splits it on the ?|? and uses whatever is before the ?|? as the dom element id in your page and the part after as the new innerHTML of that element. That means if you have a div tag like this in your page:

<div id="foo">
</div>

Once you click on that link, that will dynamically be changed to:

<div id="foo">
foo done
</div>

That?s all there is to it. Everything else is just building on top of this. Replacing my simple response ?id|text? syntax with a richer XML format and makine the request much more complicated as well. Before you blindly install large ?AJAX? libraries, have a go at rolling your own functionality so you know exactly how it works and you only make it as complicated as you need. Often you don?t need much more than what I have shown here.

Expanding this approach a bit to send multiple parameters in the request, for example, would be really simple. Something like:

function sndReqArg(action,arg) {
     http.open('get', 'rpc.php?action='+action+'&arg='+arg);
     http.onreadystatechange = handleResponse;
     http.send(null);
}

And your handleResponse can easily be expanded to do much more interesting things than just replacing the contents of a div.

Using XMLHttp

After you have created an XMLHttp object, you are ready to start making HTTP requests from JavaScript. The first step is to call the open() method, which initializes the object. This method accepts the following three arguments:

  • Request Type: A string indicating the request type to be made-typically, GET or POST (these are the only ones currently supported by all browsers).
  • URL: A string indicating the URL to send the request to.
  • Async: A Boolean value indicating whether the request should be made asynchronously.

The last argument, async, is very important because it controls how JavaScript executes the request. When set to true, the request is sent asynchronously, and JavaScript code execution continues without waiting for the response; you must use an event handler to watch for the response to the request. If async is set to false, the request is sent synchronously, and JavaScript waits for a response from the server before continuing code execution. That means if the response takes a long time, the user cannot interact with the browser until the response has completed. For this reason, best practices around the development of Ajax applications favor the use of asynchronous requests for routine data retrieval, with synchronous requests reserved for short messages sent to and from the server.

To make an asynchronous GET request to info.txt, you would start by doing this:

var oXmlHttp = zXmlHttp.createRequest();
oXmlHttp.open("get", "info.txt", true);

Note that the case of the first argument, the request type, is irrelevant even though technically request types are defined as all uppercase.

Next, you need to define an onreadystatechange event handler. The XMLHttp object has a property called readyState that changes as the request goes through and the response is received. There are five possible values for readyState:

  • 0 (Uninitialized): The object has been created but the open() method hasn't been called.
  • 1 (Loading): The open() method has been called but the request hasn't been sent.
  • 2 (Loaded): The request has been sent.
  • 3 (Interactive): A partial response has been received.
  • 4 (Complete): All data has been received and the connection has been closed.

Every time the readyState property changes from one value to another, the readystatechange event fires and the onreadystatechange event handler is called. Because of differences in browser implementations, the only reliable readyState values for cross-browser development are 0, 1, and 4. In most cases, however, you will check only for 4 to see when the request has returned:

var oXmlHttp = zXmlHttp.createRequest();
oXmlHttp.open("get", "info.txt", true);
oXmlHttp.onreadystatechange = function () {
    if (oXmlHttp.readyState == 4) {
        alert("Got response.");
    }
};

The last step is to call the send() method, which actually sends the request. This method accepts a single argument, which is a string for the request body. If the request doesn't require a body (remember, a GET request doesn't), you must pass in null:

var oXmlHttp = zXmlHttp.createRequest();
oXmlHttp.open("get", "info.txt", true);
oXmlHttp.onreadystatechange = function () {
    if (oXmlHttp.readyState == 4) {
        alert("Got response.");
    }
};
oXmlHttp.send(null);

That's it! The request has been sent and when the response is received, an alert will be displayed. But just showing a message that the request has been received isn't very useful. The true power of XMLHttp is that you have access to the returned data, the response status, and the response headers.

To retrieve the data returned from the request, you can use the responseText or responseXML properties. The responseText property returns a string containing the response body, whereas the responseXML property is an XML document object used only if the data returned has a content type of text/xml. (XML documents are discussed in Chapter 4.) So, to get the text contained in info.txt, the call would be as follows:

var sData = oXmlHttp.responseText;

Note that this will return the text in info.txt only if the file was found and no errors occurred. If, for example, info.txt didn't exist, then the responseText would contain the server's 404 message. Fortunately, there is a way to determine if any errors occurred.

The status property contains the HTTP status code sent in the response, and statusText contains the text description of the status (such as "OK" or "Not Found"). Using these two properties, you can make sure the data you've received is actually the data you want or tell the user why the data wasn't retrieved:

if (oXmlHttp.status == 200) {
    alert("Data returned is: " + oXmlHttp.responseText;
} else {
    alert("An error occurred: " + oXmlHttp.statusText;
}

Generally, you should always ensure that the status of a response is 200, indicating that the request was completely successful. The readyState property is set to 4 even if a server error occurred, so just checking that is not enough. In this example, the responseText property is shown only if the status is 200; otherwise, the error message is displayed.

The statusText property isn't implemented in Opera and sometimes returns an inaccurate description in other browsers. You should never rely on statusText alone to determine if an error occurred.

As mentioned previously, it's also possible to access the response headers. You can retrieve a specific header value using the getResponseHeader() method and passing in the name of the header that you want to retrieve. One of the most useful response headers is Content-Type, which tells you the type of data being sent:

var sContentType = oXmlHttp.getResponseHeader("Content-Type");
if (sContentType == "text/xml") {
    alert("XML content received.");
} else if (sContentType == "text/plain") {
    alert("Plain text content received.");
} else {
    alert("Unexpected content received.");
}

This code snippet checks the content type of the response and displays an alert indicating the type of data returned. Typically, you will receive only XML data (content type of text/xml) or plain text (content type of text/plain) from the server, because these content types are the easiest to work with using JavaScript.

If you'd prefer to see all headers returned from the server, you can use the getAllResponseHeaders() method, which simply returns a string containing all of the headers. Each heading in the string is separated by either a new line character (\n in JavaScript) or a combination of the carriage return and new line (\r\n in JavaScript), so you can deal with individual headers as follows:

var sHeaders = oXmlHttp.getAllResponseHeaders();
var aHeaders = sHeaders.split(/\r?\n/);

for (var i=0; i < aHeaders.length; i++) {
    alert(aHeaders[i]);
}

This example splits the header string into an array of headers by using the JavaScript split() method for strings and passing in a regular expression (which matches either a carriage return/new line couple or just a new line). Now you can iterate through the headers and do with them as you please. Keep in mind that each string in aHeaders is in the format headername: headervalue.

It's also possible to set headers on the request before it's sent out. You may want to indicate the content type of data that you'll be sending, or you may just want to send along some extra data that the server may need to deal with the request. To do so, use the setRequestHeader() method before calling send():

var oXmlHttp = zXmlHttp.createRequest();
oXmlHttp.open("get", "info.txt", true);
oXmlHttp.onreadystatechange = function () {
    if (oXmlHttp.readyState == 4) {
        alert("Got response.");
    }
};
oXmlHttp.setRequestHeader("myheader", "myvalue");
oXmlHttp.send(null);

In this code, a header named myheader is added to the request before it's sent out. The header will be added to the default headers as myheader: myvalue.

Up to this point, you've been dealing with asynchronous requests, which are preferable in most situations. Sending synchronous requests means that you don't need to assign theonreadystatechange event handler because the response will have been received by the time the send() method returns. This makes it possible to do something like this:

var oXmlHttp = zXmlHttp.createRequest();
oXmlHttp.open("get", "info.txt", false);
oXmlHttp.send(null);

if (oXmlHttp.status == 200) {
    alert("Data returned is: " + oXmlHttp.responseText;
} else {
    alert("An error occurred: " + oXmlHttp.statusText;
}

Sending the request synchronously (setting the third argument of open() to false) enables you to start evaluating the response immediately after the call to send(). This can be useful if you want the user interaction to wait for a response or if you're expecting to receive only a very small amount of data (for example, less than 1K). In the case of average or larger amounts of data, it's best to use an asynchronous call.