Here is some handy JavaScript code. See also my EG JS Includes.

Rollover with preloaded images

This rollover effect preloads images.

This code goes in the header:

function MM_preloadImages() { //v3.0
    var d=document;
    if(d.images){
        if(!d.MM_p) d.MM_p=new Array();
        var i, j=d.MM_p.length, a=MM_preloadImages.arguments;
        for(i=0; i<a.length; i++){
            if (a[i].indexOf("#")!=0){
                d.MM_p[j]=new Image;
                d.MM_p[j++].src=a[i];
            }
        }
    }
}
function MM_swapImgRestore() { //v3.0
    var i,x,a=document.MM_sr;
    for(i=0; a&&i<a.length&&(x=a[i])&&x.oSrc; i++) x.src=x.oSrc;
}
function MM_findObj(n, d) { //v3.0
    var p,i,x;
    if(!d) d=document;
    if((p=n.indexOf("?"))>0&&parent.frames.length) {
        d=parent.frames[n.substring(p+1)].document;
        n=n.substring(0,p);
    }
    if(!(x=d[n])&&d.all) x=d.all[n];
    for (i=0; !x&&i<d.forms.length; i++) x=d.forms[i][n];
    for(i=0; !x&&d.layers&&i<d.layers.length; i++){
        x=MM_findObj(n,d.layers[i].document);
    }
    return x;
}
function MM_swapImage() { //v3.0
    var i,j=0,x,a=MM_swapImage.arguments;
    document.MM_sr=new Array;
    for(i=0; i<(a.length-2); i+=3){
        if ((x=MM_findObj(a[i]))!=null){
            document.MM_sr[j++]=x;
            if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];
        }
    }
}

Preload the images:

<body onLoad="MM_preloadImages('images/zMisc/B.gif');">

Make the image a hyperlink in a format similar to the following:

<a href="index.htm"
     onMouseOut="MM_swapImgRestore()"
     onMouseOver="MM_swapImage('A.gif','','images/zMisc/B.gif',1)">
    <img name="A.gif" src="images/zMisc/A.gif" border="0">
</a>

Do more rollovers by adding to the list of preloaded images and more hyperlinked images in similar syntax.

The idea is to preload images, and then swap images on mouse events.

Here is the same idea simplified

This code goes in the header:

if (document.images){
    // ie do if there are images at all
    image1 = new Image;
    image2 = new Image;
    image1.src = "images/zMisc/A.gif";
    image2.src = "images/zMisc/B.gif";
}
function chgImg(name, image){
    if (document.images) document[name].src = eval(image+".src");
}

This code goes in the body:

<a href="/"
     onMouseOver='chgImg("AbecomesB", "image2")'
     onMouseOut='chgImg("AbecomesB", "image1")'>
        <img name="AbecomesB"
                 src="images/zMisc/A.gif"
                 border="0" /></a>

Rollover without preloading images

This code goes in the header:

<script language="jscript">
  function flipimage(url) { window.event.srcElement.src = url; }
</script>

This code goes in the body

<input
    class="button"
    Type="image"
    id="imgcmdCancel"
    SRC="../images/cancelwht.gif"
    ONCLICK="cmdCancel_Click()"
    onmouseover="flipimage('../images/cancelred.gif')"
    onmouseout="flipimage('../images/cancelwht.gif')"
    alt="Cancel">

Put a message in the Status Bar

<a href="AnyPage.htm"
     onmouseover="window.status='This link takes you to any page';
     return true">Dogs!</a>

Open pages in a different window

This example uses toc.htm to open page1.htm or page2.htm in another window.

This code should be in the headers of both page1.htm and page1.htm:

<script language="JavaScript">
<--
    window.name="mainwin"
/// -->
</script>

This code should be in the body of toc.htm:

<a href="page1.htm" target="mainwin">page1</a>
<a href="page2.htm" target="mainwin">page2</a>

Thumbnail briefly shows larger image

When the user clicks the thumbnail image, the full picture loads in a new window which can can optionally be configured to close a fixed number seconds after the page has loaded.

This code goes in the header:

<script language="JavaScript">
<!--
timeout =0;
/*
Close window after __ number of seconds?
0 = do not close, anything else = number of seconds
*/

function Start(URL, WIDTH, HEIGHT) {
windowprops = "left=50,top=50,width=" + (WIDTH+50) + ",height=" + (HEIGHT+50);

text = "<html><head><title>Preview</title></head><body bgcolor='white'";

if (timeout != 0) text +=" onLoad=\"setTimeout('window.close()', " + timeout*1000 + ");\"";

text += "><center><img src='" + URL + "'>";

if (timeout != 0) {
    text += "<br><font face='arial, helvetica' size='-1'>Preview closes after ";
    text += timeout + " seconds.</font>";

text += "</center></body></html>";

preview = window.open("", "preview", windowprops);
preview.document.open();
preview.document.write(text);
preview.document.close();
}
/// -->
</script>

This code goes in the body:

<a href="javascript:Start('http://www.your.com/images/bigpicture.gif', 267, 103)";>
<img src="http://www.your.com/images/thumbnail.gif" width=86 height=51>
</a>

Run a simple animation

Have the some event call a function to move an image from the right to the left.

Place an image tag somewhere in the body with its style attribute set as follows:

<img id="imgA"
         style="visibility:hidden; position:absolute; top:0; left:0; z-index:-1"
         src="images/YourImage.gif">

Place this code in the header:

var id;
function StartGlide() {
    document.all.imgA.style.pixelLeft = document.body.offsetWidth;
    document.all.imgA.style.visibility = "visible";
    id = window.setInterval("Glide()",50);
}
function Glide() {
    document.all.imgA.style.pixelLeft -= 10;
    if (document.all.imgA.style.pixelLeft<=0) {
        document.all.imgA.style.pixelLeft=0;
        window.clearInterval(id);
    }
}

Have some event call the first function:

<body onload="StartGlide()">

Client-side call to ASP

Use client-side code to run some server-side code by calling up an ASP.

Have the client-side code open a new window for the ASP:

strOpen = "ServerSide.asp?FileName=" + escape(FileName);
window.open(strOpen, "Processing", "width=100,height=100");

Have the server-side ASP run whatever you want and then close itself: 

<% ... 'Any non-result retuning code such as inserting into a log. %>
<html><head>
<body onload="window.close()">
</body>
</html>

This will unfortunately make a little window appear for the duration of the processing.

The same thing can be accomplished having the client-side code on an ASP open itself.

Open a new window

It's simple enough to open a file in a new window while leaving the old window in place.

You can do this in-line:

<a href="support.asp"
     onClick="window.open('support.asp', '', 'width=650,height=450');
     return false;"
>Check here if you are having a problem with our site.</a></p>

Or you can reuse script (either in the header or an included file):

function inNewWindow(pstrFile, pstrWindowName, pstrWindowFeatures) {
        var intName;
        var intFeatures;
        var strWindowName = new String(pstrWindowName);
        var strWindowFeatures = new String(pstrWindowFeatures);
        intName = strWindowName.length;
        intFeatures = strWindowFeatures.length;
        if ((intName == 0) && (intFeatures == 0)) {
                window.open(pstrFile);
        } else if (intName == 0) {
                window.open(pstrFile, '', strWindowFeatures.toString());
                        //Window Features is a list that includes:
                        //resizable, location, scrollbars, toolbar, status,
                        //height, width, top, left, 
        } else if (intFeatures == 0) {
                window.open(pstrFile, strWindowName.toString());
                        //Window Name is usu. _self, _top, etc.
        } else {
                window.open(pstrFile, strWindowName.toString(), strWindowFeatures.toString());
        }
        return false;
}

Here is a sample of your link:

<a href="support.asp"
     onClick="return inNewWindow('support.asp', '', 'width=650,height=450')"
>Check here if you are having a problem with our site.</a></p>

Make window plain

Makes the current window completely unadorned.

Place this in the header

self.menubar.visible=false;
self.toolbar.visible=false;
self.locationbar.visible=false;
self.personalbar.visible=false;
self.scrollbars.visible=false;
self.statusbar.visible=false;

Trim Strings

These two functions trim a string of white space from its left and right sides respectively.

function lTrim(s) { return s.replace(/^\s*/,""); }
function rTrim(s) { return s.replace(/\s*$/,""); }

The preceding two functions can be combined into a third function to trim a string of white space on both of its sides.

function trim(s) { return rTrim(lTrim(s)); }

Alternatively, this bit of code allows the String object to trim any white space from either side of its string.

String.prototype.trim = function() {
    return this.replace(/^\s*(\b.*\b|)\s*$/, "$1");
}

Frequently characters at the end or the beginning of a string need to be trimmed. There are many ways to do this.

'foo'.slice(1); //returns 'oo'
'bar'.slice(0, -1); //returns 'ba'
Pad an ID with zeroes

This takes an integer and pads the left size with zeroes.

function gPad(str,intPlaces) {
// assumes that places >= length
    var intLength = str.length;
    var intDifference = intPlaces-intLength;
    while (intDifference>0) {
        str = "0"+str;
        intDifference--;
    }
    return str;
}

Check string length or number range

This function takes a number and checks if its values is within a certain range.

function isNumBetween(n, min, max) {
    return(
        (n >= (min!=null ? min : Number.MIN_VALUE)) &&
        (n <= (max!=null ? max : Number.MAX_VALUE))
    );
}

This function takes a string and check if its length is within a certain range.

function isLenBetween(s, min, max) {
    return(
        (s >= (s.length >= (min!=null ? min : 0)) &&
        (s <= (s.length <= (max!=null ? max : Number.MAX_VALUE))
    );
}

This function combines the previous two functions so it can check for either string length or number range.

function isBetween(a, min, max) {
    if(isNAaN(a)) return isLenBetween(a, min, max);
    else return isNumBetween(a, min, max);
}

Hide/Show a list

Here is a typical list:

<p>The 3 Friends</p>
<ul>
    <li>Tom</li>
    <li>Dick</li>
    <li>Harry</li>
</ul>

Here is the above list modified so it can hide and show. It starts out as showing the full list.

<p>The 3 Friends. <a id="btn3Friends" onclick="return hideShow(this,lst3Friends);"><<</a></p>
<ul id="lst3Friends">
    <li>Tom</li>
    <li>Dick</li>
    <li>Harry</li>
</ul>

This function would be in the header:

function hideShow(btn,obj) {
    if (btn.innerText == "<<") {
        btn.innerText = ">>";
        obj.style.display = "none";
    } else {
        btn.innerText = "<<";
        obj.style.display = "block";
    }
}

Hide/Show Next Element

A typical use case is to have a label (say h3) and its content (say div). When you click on the label, then its content is hidden or shown.

To implement with the least amount of work:

<h3 onclick="showHideNext(this);">Section 1</h3>
<div>
    <p>foo</p>
    <p>bar</p>
</div>

<h3 onclick="showHideNext(this);">Section 2</h3>
<div>
    <p>hoo</p>
    <p>hey</p>
</div>
function showHideNext(myLabel) {
    var myTarget = myLabel.nextElementSibling;
    if (myTarget.style.display === 'block') {
        myTarget.style.display = 'none';
    } else {
        myTarget.style.display = 'block';
    }
}

There are many variants of this such as whether the content is hidden or shown to start with, or whether there is some sort of visual indicator like +/- or <</>>. You can figure out these variants with these clues:

<h3 onclick="showHide(this, 'section1');">Section 1 [-]</h3>
<div id="section1" class="open" >
    <p>foo</p>
    <p>bar</p>
</div>

<h3 onclick="showHide(this, 'section2');">Section 2 [+]</h3>
<div id="section2" class="closed" >
    <p>hoo</p>
    <p>hey</p>
</div>
function showHide(myLabel, nameOfTarget) {
    var myTarget = document.getElementById(nameOfTarget);
    if (myTarget.className === 'open') {
        myTarget.innerHTML = myLabel.innerHTML.replace("[-]","[+]");
        myLabel.className = 'closed';
        myTarget.style.display = 'none';
    } else {
        myLabel.innerHTML = myLabel.innerHTML.replace("[+]","[-]");
        myTarget.className = 'open';
        myTarget.style.display = 'block';
    }
}
<style>
    .open {
        display: block;
    }
    .closed {
        display: none;
    }
</style>

Reverse Letters

This bit a script take a string and returns a string with the letters of the string entered in reverse order.

var str1 = "hello world!";
var str2;
for (count=str1.length; count>=0; count--)
        str2+=str1.substring(count,count-1);
// str2 should now equal "!dlrow olleh"

Generate random integer for a given range

This function returns a random number between 0 and 1.

function random01() {  return Math.random()  }

This function returns a random integer between 0 and n inclusively, assuming integer n > 0.

function random0N(n) {  return Math.round(Math.random()*n)  }

This function returns a integer between n and m inclusively, assuming integer end > beg.

function randomMN(beg, end){  return beg + Math.round(Math.random()*(end-beg))  }

Timer then transfer user to another page

This function will transfer the user to another page after a specified pause.

function transfer() {
    var intPause = 5; //Seconds before transfer
    intPause *= 1000;
    setTimeout('window.location="http://www.google.com/"',intPause);
}

Transfer values between pages as if you were serverside

Via http://www.ghtml.com/pickpocket/getvalues.php?author=geeeet&content=ghtml.

This code needs some work to be functional.

<head>
...
<script language="javascript" type="text/javascript">
function getValues(){
    var urlEnd = document.URL.indexOf('?');
    var values = new Array();
    var names;

    if (urlEnd != -1){
        var params = document.URL.substring(urlEnd+1, document.URL.length).split('&');
        for(i=0; i<params.length; i++) {
            names = params[i].split('=');
            values[names[0]] = names[1];
        }
    }
    return values;
}
values = getValues();
</script>

Have a form submit different actions

You can have a form submit different actions either on the client side or the client & server side.

Here is a sample of the client side option. The first block is the script in the header.

function validOther(act){
    var form = document.fOther;
    // Do misc form validation 1st then:
    switch(act){
    case "Edit":
            form.action = "Edit.asp";
            break;
    case "Delete":
            form.action = "Delete.asp";
            break;
    }
    return true;
}
<form id="fOther" name="fOther" method="POST">
// ...<input type="submit" value="Edit" name="Edit" id="Edit" onClick="validOther('Edit')" />
<input type="submit" value="Delete" name="Delete" id="Delete" onClick="validOther('Delete')" />
</form>

Alternatively:

function onsubmitting(form){
        // Do misc form validation 1st then:
        switch(act){
        case "Edit":
                form.action = "Edit.asp";
                break;
        case "Delete":
                form.action = "Delete.asp";
                break;
        }
        return true;
}
<form id="fOther" name="fOther" method="POST" onsubmit="return onsubmitting(this);">
// ...<input type="submit" value="Edit" name="Edit" id="Edit" onclick="act='Edit';" />
<input type="submit" value="Delete" name="Delete" id="Delete" onclick="act='Delete';" />
</form>

To do it on the client and server side, have a hidden field accept whatever the desired action should be.

<input type="hidden" name="toDoOnServerSide" />

Then simply read that field on the server side (CGI, ASP, PHP, whatever) and do whatever depending upon the value.

To make sure an option is chosen from a select list

When you have a select list, you could have a default item chosen. However if you want to make the user select an option, make the default option a fake option.

<select size="3" name="select1" id="select1">
<option value="0" selected="selected">To Edit or Delete, select an option then press "Edit" or "Delete"</option>
<option value="1">Connie</option>
<option value="2">York</option>
<option value="3">Amy</option>
</select>

The validation code would be something like this:

function valid(){
    if (document.form1.select1.options[0].selected){
        alert("You must select an Person");
        return false;
    }
}

To validate radio input

This validation code makes sure that a radio input is selected.

function valid(form){
    var blnRadio = false;
    for(i=0; i<form.radioX1.length; i++){
        if (form.radioX1[i].checked) blnRadio = true;
    }
    if(!blnRadio ){
        alert("Please select an option.")
        return false;
    }
    return true;
}

To check a bunch of radio questions try this:

function validate(form){
    var blnRadio = false;
    var radioX;
    for(var i=0; i<=9; i++){
        radioX = eval("form.q"+i);
        for(var j=0; j<radioX.length; j++){
            if(radioX[j].checked){
                blnRadio = true;
                break;
            }
        }
        if(!blnRadio){
            alert('Please answer question '+i+'.');
            return false;
        }
        blnRadio = false;
    }
    return true;
}

Converting between binary, octal, decimal, and hexadecimal

This bit of code converts between binary, octal, decimal, and hexadecimal numbers. I got this from skyzyx.com/scripts/convert.php.

Here is the code referenced:

CONVERSIONS
By Ryan Parman
Distributed according to SkyGPL 2.1, http://www.skyzyx.com/license/
*******************************************************/
function decimal(dec){
    this.dec=dec;
    this.toBinary=function() { return this.dec.toString(2); }
    this.toHex=function() { return this.dec.toString(16).toUpperCase(); }
    this.toOctal=function() { return this.dec.toString(8); }
}
function binary(bin){
    this.bin=bin;
    this.toDecimal=function() { return parseInt(this.bin, 2); }
    this.toHex=function() { return this.toDecimal().toString(16).toUpperCase(); }
    this.toOctal=function() { return this.toDecimal().toString(8); }
}
function hex(hex){
    this.hex=hex;
    this.toDecimal=function() { return parseInt(this.hex, 16); }
    this.toBinary=function() { return this.toDecimal().toString(2); }
    this.toOctal=function() { return this.toDecimal().toString(8); }
}
function octal(oct){
    this.oct=oct;
    this.toDecimal=function() { return parseInt(this.oct, 8); }
    this.toBinary=function() { return this.toDecimal().toString(2); }
    this.toHex=function() { return this.toDecimal().toString(16).toUpperCase(); }
}

Here is typical usage of the code:

new hex("FF").toDecimal(); // Returns 255

Check if something is an integer

Often you will check if a parameter or a form control has an integer. I've surfed around for different solutions and most are more complex (usually using parseInt). This quick and dirty solution is the smallest I've seen.

function isInteger(s) {
        return (s.toString().search(/^-?[0-9]+$/) == 0);
}
function isUnsignedInteger(s) {
        return (s.toString().search(/^[0-9]+$/) == 0);
}
Both via "JavaScript isInteger Function" [http://surf11.com/entry/157/javascript-isinteger-function]

Calculating age assuming good DOB

function CalculateAge(YB,MB,DB){
    var Now=new Date();
    var Today=new Date(Now.getFullYear(),Now.getMonth(),Now.getDate());
    var DOB=new Date(YB,MB,DB); //Note month is 0-11
    var Age=Today.getFullYear()-YB;
    if (
            (MB>Today.getMonth()) ||
            (MB==Now.getMonth() &&DB>Today.getDate())
    ) {
            Age--;
    }
    document.write(Age);
}

Abbreviate magnitudes

This may not be commonly used but I thought it was a beautiful bit of code by Dr JR Stockton at http://groups.google.com/group/comp.lang.javascript/browse_thread/thread/16e76a4c1ce38b0f?hl=en on 2008-09-27.

S = "$1000000000"
S = S.replace(/(0+)$/, function(a, s) { var L = s.length
    return ['','0','00'][L%3] + ['','K','M','G','T','P','E'][(L/3)|0]})
// S is now "$100M"

Binary Tree

Implement a small binary tree with just an array. A binary tree represents data in a tree of nodes where each node has a value and two child nodes (left and right).

var binaryTree = [0, 1, 2, 3, 4, 5, 6];
function leftChild(bt, i) {
        return bt[2i + 1];
}
function rightChild(bt, i) {
        return bt[2i + 2];
}


GeorgeHernandez.comSome rights reserved