Javascript

Image Rollovers

A favorite technique to add some pseudo-excitement is to swap button images as the user rolls the cursor atop them.The degree of change is largely matter of taste.The effect can be subtle-a slight highlight or glow around the edge of the image-or drastic-a radical change of color.Whatever your approach the scripting is the same.

Code:

<html>
 <head>
 <title>Image Rollovers</title>
 <script type="text/javascript">
 if(document.images)
 {
   var offImage = new Array();
   offImage['play'] = new Image(80,30);
   offImage['stop'] = new Image(80,30);
   offImage['pause'] = new Image(80,30);
   offImage['rewind'] = new Image(80,30);
   offImage['play'].src = "images/playoff.png";
   offImage['stop'].src = "images/stopoff.png";
   offImage['pause'].src = "images/pauseoff.png";
   offImage['rewind'].src = "images/rewindoff.png";
   var onImage = new Array();
   onImage['play'] = new Image(80,30);
   onImage['stop'] = new Image(80,30);
   onImage['pause'] = new Image(80,30);
   onImage['rewind'] = new Image(80,30);
   onImage['play'].src = "images/playon.png";
   onImage['stop'].src = "images/stopon.png";
   onImage['pause'].src = "images/pauseon.png";
   onImage['rewind'].src = "images/rewindon.png";
 }
 function imageOn(imgName)
 {
   if(document.images)
   {
     document.images[imgName].src = onImage[imgName].src;
   }
 }
 function imageOff(imgName)
 {
   if(document.images)
   {
     document.images[imgName].src = offImage[imgName].src;
   }
 }
 function setMsg(msg)
 {
   window.status = msg;
   return true;
 }
 </script>
 </head>
 <body>
 <form>
 Image Rollover
 <a onmouseover="imageOn('play'); return setMsg('Play the selected tune')"
 onmouseout="imageOff('play'); return setMsg('')">
 <img src="images/playoff.png" name="play" width="80" height="30" border="0" />
 </a>
 <a onmouseover="imageOn('stop'); return setMsg('Stop the selected tune')"
 onmouseout="imageOff('stop'); return setMsg('')">
 <img src="images/stopoff.png" name="stop" width="80" height="30" border="0" />
 </a>
 <a onmouseover="imageOn('pause'); return setMsg('Pause the selected tune')"
 onmouseout="imageOff('pause'); return setMsg('')">
 <img src="images/pauseoff.png" name="pause" width="80" height="30" border="0" />
 </a>
 <a onmouseover="imageOn('rewind'); return setMsg('Rewind the selected tune')"
 onmouseout="imageOff('rewind'); return setMsg('')">
 <img src="images/rewindoff.png" name="rewind" width="80" height="30" border="0" />
 </a>
 </form>
 </body>
 </html>

Precaching Images

Javascript enabling scripts to load images into the browser’s memory cache without displaying the image, a technique called precaching images.

Precaching an image requires constructing an image object in memory:

var myImage = new Image(width, height);

parameters to the constructor function are the pixel width and height of the image.

Code:

<html>
 <head>
 <title>Image Object</title>
 <script type="text/javascript">
 var imageArray = new Array();
 imageArray['image1'] = new Image(100, 100);
 imageArray['image1'].src = "img1.gif";
 imageArray['image2'] = new Image(100, 100);
 imageArray['image2'].src = "img2.gif";
 imageArray['image3'] = new Image(100, 100);
 imageArray['image3'].src = "img3.gif";
 function loadImages(list)
 {
   var img = list.options[list.selectedIndex].value;
   document.thumb.src = imageArray[img].src;
 }
 </script>
 </head>
 <body>
 <h3>Image Object</h3>
 <img src="img1.gif" name="thumb" width="100" height="100" />
 <form>
 <select onchange="loadImages(this)">
 <option value="image1">Image 1</option>
 <option value="image2">Image 2</option>
 <option value="image3">Image 3</option>
 </select>
 </form>
 </body>
</html>

References for Multiple Windows

This example demonstrates how subwindows can communicate with objects, functions and variables in the window or frame that creates the subwindow.

Every window object has a property called opener, this property contains a reference to the window or frame that held the script whose window.open( ) statement generated the subwindow, for the main window or frame this value is null.

Code:

Main Window

<html>
 <head>
 <title>Main Window</title>
 <script type="text/javascript">
 function newWindow()
 {
   window.open("subwindow.html", "subwindow", "width=300,height=300");
 }
 </script>
 </head>
 <body>
 <form>
 <input type="button" value="New Window" onclick="newWindow()" />
 <br />
 Text from subwindow:
 <input type="text" name="txt" />
 </form>
 </body>
</html>

Subwindow

<html>
 <head>
 <title>Subwindow</title>
 </head>
 <body>
 <form onsubmit="return false">
 <input type="text" name="txt2" />
 <input type="submit" onclick="opener.document.forms[0].txt.value = document.forms[0].txt2.value" />
 </form>
 </body>
</html>

Note: the parent-child terminology doesn’t apply to subwindows.


Date Object Calculations

Performing calculations with dates frequently requires working with the millisecond values of the Date objects, this is the surest way to compare date values.

Code:

<html>
 <head>
 <title>Date Calculations</title>
 <script type="text/javascript">
 function nWeek()
 {
   var todayMillisec = today.getTime();
   var nWeekMillisec = todayMillisec + (60*60*24*7*1000);
   var dayNextWeek = new Date(nWeekMillisec);
   return dayNextWeek;
 }
 </script>
 </head>
 <body>
 Today is:
 <script type="text/javascript">
 var today = new Date();
 document.write(today);
 </script>
 <br />
 Next week will be:
 <script type="text/javascript">
 document.write(nWeek());
 </script>
 </body>
</html>

In this example you could eliminate the function entirely and let the following two statements in the second body script obtain the desired result:

today.setDate(today.getDate() + 7);

document.write(today);


Date Object

Date is a global object ready to be called upon at any time, the Date is  a static object. When you wish to work with a date, you must to invoke the  Date object constructor function to obtain an instance of a Date object. The value of a Date object is the time in milliseconds from zero o’clock on 1/1/ 1970. You can also grab a snapshot of the Date object for a particular date and time in the past or future by specifying that information as parameters to the Date object constructor function:

var dateObj = new Date(”Month dd, yyyy”);

Date object methods

var dateObj = new Date( );

  • method dateObj.getTime( )
  • value 0-…
  • description milliseconds since 1-1-1970 GTM

———————————————

  • method dateObj.getYear( )
  • value 70-…
  • description minus 1900;four-digit year for 2000+

———————————————

  • method dateObj.getFullYear( )
  • value 1970-…
  • description four-digit year

———————————————

  • method dateObj.getMonth( )
  • value 0-11
  • description month within the year

———————————————

  • method dateObj.getDate( )
  • value 1-31
  • description date within the month

———————————————

  • method dateObj.getDay( )
  • value 0-6
  • decsription day of week

———————————————

  • method dateObj.getHours( )
  • value 0-23
  • description hour of the day (24 hour time)

———————————————

  • method dateObj.getMinutes( )
  • value 0-59
  • description minute of the hour

———————————————

  • method dateObj.getSeconds( )
  • value 0-59
  • description second within a minute

———————————————

  • method dateObj.setTime( )
  • value 0-…
  • decsription milliseconds since 1-1-1970 GTM

———————————————

  • method dateObj.setYear( )
  • value 70-…
  • description minus 1900;four digit year for 2000+

———————————————

  • method dateObj.setMonth( )
  • value 0-11
  • description month within a year

———————————————

  • method dateObj.setDate( )
  • value 1-31
  • description date within the month

———————————————

  • method dateObj.setDay( )
  • value 0-6
  • description day of week

———————————————

  • method dateObj.setHours( )
  • value 0-23
  • description hour of the day (24 hour time)

———————————————

  • method dateObj.setMinutes( )
  • value 0-59
  • description minute of the hour

———————————————

  • method dateObj.setSeconds( )
  • value 0-59
  • description second within the minute

———————————————

Note: the getMonth( ) and setMonth( ) method values are zero based; January is 0, December is 11.


Passing Form Data and Elements to Functions

Javascript features a keyword this that always refers to object contains the script in which the keyword is used.

<input type=”text” name=”textfield” onchange=”myfunction(this)” /> the keyword this pass a reference of the text object to the function.

<input type=”button” value=”click” onclick=”myfunction(this.form)” /> a reference to the entire form, rather than just the object calling the function.

Code:

<html>
 <head>
 <title>Beatle picker</title>
 <script type="text/javascript">
//---------------------------------------------------------------------
 function myfunction_A(form)
 {
   for(var i=0; i<form.Beatles.length; i++)
   {
     if(form.Beatles[i].checked)
     break;
   }
   var beatle = form.Beatles[i].value;
   var song = form.song.value;
   alert(song + " " + beatle);
 }
//--------------------------------------------------------------------
 function myfunction_B(entry)
 {
   var song = entry.value;
   alert(song);
 }
//--------------------------------------------------------------------
 </script>
 </head>
 <body>
 <p>
 <form onsubmit="return false">
 <input type="radio" name="Beatles" value="John Lennon" checked />John
 <input type="radio" name="Beatles" value="Paul McCartney" />Paul
 <input type="radio" name="Beatles" value="George Harrison" />George
 <input type="radio" name="Beatles" value="Ringo Star" />Ringo
 </p>
<p>
 <input type="text" name="song" value="Eleanor Rigby" onchange="myfunction_B(this)"/>
 <input type="submit" name="process" value="Process" onclick="myfunction_A(this.form)" />
 </p>
 </form>
 </body>
 </html>

Submitting and Prevalidating Forms

Before a form is submitted we perform a validation of data in the form. We can do this in a function invoked by the form’s onsubmit event handler.

Code:

<html>
 <head>
 <title>Prevalidating Data</title>
 <script type="text/javascript">
//----------------------------------------------------
 function check(form)
 {
   for(var i=0; i<form.elements.length; i++)
   {
     if(form.elements[i].value == "")
     {
       alert("Field:" + form.elements[i].name + " empty");
       return false;
     }
   }
   return true;
 }
//--------------------------------------------------
 </script>
 </head>
 <body>
 <form onsubmit="return check(this)">
 First name: <input type="text" name="firstName" /><br />
 Last name: <input type="text" name="lastName" /><br />
 <input type="submit" value="Submit" />
 </form>
 </body>
 </html>

Ajax XMLHttpRequest

The function below creates a XMLHttpRequest object; sends the request to the server and finaly receives the data.

Variables:

target: the ID of the HTML element where the rensponse message is displayed.

method: POST or GET.

url: server side script that receives the request.

param: the data.

slideIt: (milliseconds) determines the duration of the rensponse message occurence.

loadImage: If is not zero (0) load an image during the request proccess; its value is the ID of the HTML element where the image appears.

shoWait: displays a message during the request proccess; if its value is zero (0) nothing happens else the value is the message.

Code:

function Ajaxify(target, method, url, param, slideIt, loadImage, shoWait)
{
  if(shoWait != 0)
  {
    document.getElementById(target).innerHTML = shoWait;
  }
  if(loadImage != 0)
  {
    document.getElementById(loadImage).innerHTML = '<img src="my_image.gif"/>';
  }
 //Find Correct XMLHTTP Connection
 if(!window.XMLHttpRequest)
 {
   window.XMLHttpRequest = function()
   {
     var types = [
    'Microsoft.XMLHTTP',
    'MSXML2.XMLHTTP.5.0',
    'MSXML2.XMLHTTP.4.0',
    'MSXML2.XMLHTTP.3.0',
    'MSXML2.XMLHTTP'
    ];
    for(var i = 0; i < types.length; i++)
    {
      try
      {
        return new ActiveXObject(types[i]);
      }
      catch(e)
      {}
    }
    return false;
   };
 }
 //Create Socket
 NewRequest = new XMLHttpRequest();
 NewRequest.open(method, url, true);
 NewRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 NewRequest.send(param);
 NewRequest.onreadystatechange = function()
 {
   if (NewRequest.readyState == 4)
   {
     if (NewRequest.status == 200)
     {
       if(loadImage != 0)
       {
         document.getElementById(loadImage).innerHTML = '';
       }
       if(slideIt != 0)
       {
         var comment = new Fx.Slide(target, {duration: slideIt}).hide();
       }
       document.getElementById(target).innerHTML = unescape(NewRequest.responseText);
       if(slideIt != 0)
       {
         comment.toggle();
       }
     }
     else
     {
       document.getElementById(target).innerHTML = 'Ajax Error';
     }
   }
 };
 }

The Select Object

The most complex form control to script is the select element object, this object contains an array of options objects.Some properties belong to the entire select object; others belong to individual options inside the select object.The most important property of the select object is the selected property document.myform.selectName.selectedIndex.

Other properties of an option object are text and value:

document.myform.selectName.options[i].text

document.myform.selectName.options[i].value

Code:

<html>
 <head>
 <title>Select Object</title>
 <script type="text/javascript">
//----------------------------------------------------
 function myfunction()
 {
   var selectList = document.forms[0].myselect;
   alert("Selected text:" + selectList.options[selectList.selectedIndex].text + "\n" +
   "Selected value:" + selectList.options[selectList.selectedIndex].value);
 }
//---------------------------------------------------
 </script>
 </head>
 <body>
 <form>
 <select name="myselect" onchange="myfunction();">
 <option value="1">Home</option>
 <option value="2">Browse</option>
 <option value="3">Search</option>
 </select>
 </form>
 </body>
</html>

Radio Object

The example demonstrates how to look throught a group of buttons to find out which one is checked and how to use the value attribute.

Note : Members of a group of radio objects must have the same name. Multiple groups can exists within a form but each member of the same group must share the same name.

Code:

<html>
<head>
<title>
Radio Button
</title>

<script type=”text/javascript”>

function myfunction()
{
var myform = document.forms[0];

for(var i=0; i<myform.countries.length; i++)
{
if(myform.countries[i].checked)
break;
}

alert(myform.countries[i].value);
}

</script>

</head>

<body>
<form>
<input type=”radio” name=”countries” value=”Italy” checked />
<input type=”radio” name=”countries” value=”France”  />
<input type=”radio” name=”countries” value=”England” />
<input type=”radio” name=”countries” value=”Spain” />
<input type=”button” value=”Click” onClick=”myfunction();” />
</form>
</body>
</html>