9 Javascript(s) you better not miss !!

This tutorial is aimed at those who have a working knowledge of Javascript. So the examples are not explained in great detail. Only the important parts are highlighted. I have presented 9 Javascript examples that I have found very useful while designing professional websites. There are many ways to implement these examples here. The code presented here is neither the shortest nor the most efficient. But it does work satisfactorily.

Please not that that wherever there is a mention of any .jpg , .gif or any other .html files, see to it that you have a dummy .gif, .jpg or .html file in the same directory as the script file so that the script finds these files. They can be any files since the logic of the script doesn't depend on these files. Try to understand the way the examples work, and you will be able to modify them and make them more useful. Also note that the entire code for the html page is not present here. Only the script and the relevant html is present.


Example 1 : A Single click for checking-unchecking multiple check boxes
You must have seen this script working at many places. One that comes to my mind is at Yahoo / Hotmail for checking or unchecking all the mails that are visible on the page. There are lots of places where you can use this script, generally when you want the user to carry out some task on either all or none of the items that you present to him.

<SCRIPT LANGUAGE = "JavaScript">
<!--
function modify_boxes(to_be_checked,total_boxes){
  for ( i=0 ; i < total_boxes ; i++ ){
    if (to_be_checked){
  document.forms[0].chkboxarray[i].checked=true;
}
    else{
   
document.forms[0].chkboxarray[i].checked=false;
    }
  }  
}
   
-->
</SCRIPT>


<BODY>
<FORM>
<INPUT TYPE=checkbox NAME="chkboxarray" VALUE="1"><br>
<INPUT TYPE=checkbox NAME="chkboxarray" VALUE="2"><br>
<INPUT TYPE=checkbox NAME="chkboxarray" VALUE="3"><br>
<INPUT TYPE=button NAME="CheckAll" VALUE="Check All Boxes" onClick="modify_boxes(true,3)">
<INPUT TYPE=button NAME="UnCheckAll" VALUE="UnCheck All Boxes" onClick="modify_boxes(false,3)">
</FORM>
</BODY>

Note : The VALUE tag for the checkboxes seem to have no use. But it is required to differentiate between the check boxes when you submit such a form to a server side program. You could differentiate between the checked boxed by giving different VALUEs to the checkbox.


Example 2 : Opening a page (existing as well as dynamic) in a new window without bars, buttons, etc.
This script shows how to open a new page inside a new window rather than the existing window. You can also remove all the buttons and toolbars that exist in the standard browser window so that the entire new window is filled with only your content. You could either open an existing page or you could create dynamic content inside the new window.

<SCRIPT LANGUAGE = "JavaScript">
<!--

function open_new_window() {
  dlg = window.open ("newpage.html" ,"NewWindowName" , "width=400,height=400,
toolbar=no,location=no,directories=no,
status=no,menubar=no,scrollbars=no,resizable=no")

}

function open_new_window2() {

  dlg = window.open ("","NewWindowName2","width=400,height=400,toolbar=no,location=no,
directories=no,status=no,menubar=no,scrollbars=no,resizable=no")
dlg.document.write ("<BODY bgColor='#FFFFFF'>")
dlg.document.write ("<CENTER>This is text that has been added on the fly using Javascript.</CENTER>")
dlg.document.write ("</BODY>")

}
-->
</SCRIPT>

<BODY>
<A onClick='open_new_window()' >Click anywhere on this text to open the file newpage.html in a new window</a><br>

Or click on the button below to open a dynamically generated html page<br>

<FORM>
<INPUT type="button" value="New Window" onClick ='open_new_window2()' >
</FORM>
</BODY>



Example 3 : Multiple submit buttons on a single form (Submitting same form to any one of many programs)
This script shows you how to submit the contents of a form to different programs depending on which Submit button you press. Additionally it also shows how to call two different functions when you press the Submit button.

When you press submit on this script it first sets the variable totalboxes = 2, then it also sets the target for the form using the 3 if conditions stated. Then it calls the isReady() function and checks to see if atleast one checkbox has been checked. If even one is checked then it returns true and this causes the contents to be submitted to either program1.jsp or program2.jsp or program3.jsp. If even one checkbox wasn't checked you would be notified with a alert dialog box.

<SCRIPT LANGUAGE = "JavaScript">
<!--

var totalboxes;

function setCount(count, target){
 

totalboxes=count;

// the next 3 lines are the main lines of this script
//remember to leave action field blank when defining the form
if(target == 0) document.myform.action="program1.jsp";
if(target == 1) document.myform.action="program2.jsp";
if(target == 2) document.myform.action="program3.jsp";

}

function isReady(form) {

  for(var x=0 ; x<totalboxes ; x++){

//if even one box is checked then return true
if(myform.boxes[x].checked) return true;
}  
 

//default action : When even one was not checked then..
alert("Please check at least one checkbox..");
return false;

}

//-->
</SCRIPT>

<BODY>

<FORM onSubmit="return isReady(this)" METHOD="post" NAME="myform" ACTION="">
<INPUT TYPE="checkbox" NAME="boxes" VALUE="box1">Box 1 <BR>
<INPUT TYPE="checkbox" NAME="boxes" VALUE="box2">Box 2 <BR>
<INPUT TYPE="checkbox" NAME="boxes" VALUE="box2">Box 3 <BR>
<INPUT TYPE="checkbox" NAME="boxes" VALUE="box2">Box 4 <BR>
<INPUT TYPE="checkbox" NAME="boxes" VALUE="box2">Box 5 <BR>
</FORM>

<INPUT TYPE="image" onClick="setCount(5,0)" NAME="Submit1" VALUE="delete" SRC="delete_icon.jpg">
<INPUT TYPE="image" onClick="setCount(5,1)" NAME="Submit2" VALUE="view" SRC="view_icon.jpg">
<INPUT TYPE="image" onClick="setCount(5,2)" NAME="Submit3" VALUE="modify" SRC="modify_icon.jpg">

</BODY>

The setCount() take 2 parameters, the no of checkboxes and the target program to which the contents have to be submitted to.

Note : Sending the variable 5 for no of boxes using the onClick() event is useful in case you are not knowing the no. of checkboxes while writing the top part of the html page (while writing the script part at the top of the page). This may happen in case you are dynamically creating this html page then you may not know how many checkboxes would be present in the beginning. Basically this thing becomes useful since the dynamic languages such as ASP or JSP would generate the page line by line and at that time you would first generate the script part and then the actual checkboxes on the page. So you would not be able to set the value of totalboxes to a finite number before actually adding all the checkboxes to the page. You could use a counter (within ASP/JSP) which keeps track of the checkboxes you add to the html page and finally set the value of that counter as a parameter to this onClick() function.
You could avoid this by typing the Script at the bottom of the page, but that doesn't work with a few browsers. In case you haven't got the point, its ok.. Just understand how to submit the form to different programs. You can leave the checkbox part...


Example 4 : Emulating Browsers Back-Forward buttons
This is a simple script that many programmers know. Most of the users feel that this is a waste since the browsers Forward-Back buttons are already present. But you would realize that in case you are creating a window without the standard toolbars as shown in Example No.3 , then you would find this script to be very useful to emulate the Browsers buttons.

I have shown 2 ways.. I prefer the image one, since it looks really neat in case you have nice image.

<BODY>
<FORM>
<INPUT TYPE="image" SRC="N.jpg" NAME="back" onClick="window.history.go(-1)">
<INPUT TYPE="button" VALUE="Go Back" NAME="back" onClick="window.history.go(-1)">
<INPUT TYPE = "button" VALUE = "GO Forward" onClick = "window.history.go(1);">
</FORM>
</BODY>


Example 5 : Making the Output of a program (servlet/cgi program) to appear in a new frame
This script is used by most many programmers. I haven't found this script to be very helpful, since I try my best to avoid using frames on my website. Frames are to be avoided whenever, wherever possible. And I always manage without them.

<HTML>
<FRAMESET COLS="20%,*">
<FRAME SRC="leftindex.html" NAME="Left frame" >
<FRAME SRC="rightindex.html" NAME="Right frame">
</FRAMESET>
</HTML>

Below is the source of leftindex.html

<HTML>
<BODY>
<FORM NAME="Myform" METHOD=GET
ACTION="http://www.kiranpai.com/servlet1" onSubmit="document.myform.target = 'Right frame'>
<INPUT TYPE=SUBMIT VALUE="Clicking in left frame but Output in Right frame">
</FORM>
</BODY>
</HEAD>


Example 6 : Displaying a Countdown using Javascript
You require 5 images named countdown1.jpg, countdown2.jpg ..so on till countdown5.jpg each with repective digits on them, in the same directory as the script. When you load this page, after a delay of 2 seconds the images are displayed in the reverse order (from 5 down to 1) each after a delay of 1 second. This gives it a kewl effect of a countdown from 5 to 1 and then when it finishes a new blank window opens. The opening of a blank window was the simplest thing to use here. You can replace that with any other command.

I had used a slightly modified version of this countdown script during a press release of one of the websites I had developed. After the countdown the website opened in the new window. Ofcourse it was accompanied with claps and wows from the crowd present there :-) The effects looked wonderful since I had used 5 animated gifs, with each of them showing a sort of transformation (morphing) from one digit to another.

<SCRIPT LANGUAGE = "JavaScript">
<!--

x=5;
var pics= new Array();

for(i=1;i<=x;i++){
  pics[i]=new Image();
pics[i].src="countdown"+i+".jpg";
}

function img(){
  document.images[0].src=pics[x].src;
x--;
if(x>0) setTimeout('img()',1000);
if(x==0) setTimeout("msg=open('','DisplayWindow')",1000);

}
-->
</script>

<BODY onLoad="setTimeout('img()',2000)">
<B>The countdown from 5 to 1 will begin in 2 seconds</B>
</BODY>


Example 7 : Changing images with MouseOver and MouseOut events
This is probably the most common use of Javascript. There are countless ways to get this working, but I present one that I use frequently. This script like many of my other ones rely on numbered image files. Make images with names such as org0.jpg, org1.jpg and org2.jpg. These would be initially displayed. Get 3 more files named new1.jpg, new2.jpg and 3.jpg which would be the files displayed when the mouse is over the original images.

<SCRIPT LANGUAGE = "JavaScript">
<!--

function new_img(no){
  document.images[no].src="new"+no+".jpg";
}

function org_img(no){
  document.images[no].src="org"+no+".jpg";
}
-->
</SCRIPT>

<BODY>
<IMG SRC="org0.jpg" onMouseOver="new_img(0)" onMouseOut="org_img(0)">
<IMG SRC="org1.jpg" onMouseOver="new_img(1)" onMouseOut="org_img(1)">
<IMG SRC="org2.jpg" onMouseOver="new_img(2)" onMouseOut="org_img(2)">
</BODY>

Alternatively in case you want to change an image when clicked on it use the following script

<SCRIPT LANGUAGE = "JavaScript">
<!--

function change_img(index){
  document.images[index].src = "N.jpg";

}
-->
</SCRIPT>

<BODY>
<A HREF="JavaScript: change_img(0)"><IMG SRC="I.jpg"></A>
</BODY>


Example 8 : Checking the form contents before submitting the form
This is once again an extremely important use of Javascript (this was one of the primary uses of Javascript). It reduces the time and resources on the server side for checking of online forms. Once again I have found many implementations of this script. This is one I find easy to understand.


<SCRIPT LANGUAGE = "JavaScript">
<!--
function isReady(recv_form) {
  if (recv_form.feedback.value != "")
    return true;
  else {
    alert("Please include a feedback message.");
recv_form.feedback.focus();
return false;
}
}
//-->
</SCRIPT>

<BODY>
<FORM NAME = "myform" onSubmit = "return isReady(this)" METHOD=POST ACTION = "http://www.kiranpai.com/servlet1">
<TEXTAREA NAME = "feedback"></TEXTAREA><br>
<INPUT TYPE="submit" VALUE="Submit">
</FORM>
</BODY>


Example 9 : Filling the values of a dropdown SelectMenu depending on the selection in another Menu
If you are developing a professional site for a company you would invariably come across a situation where you are expected to do the above. Remember that the power of this script becomes evident when you use Javascript along with some other dynamic language such as JSP or ASP. You could probably fill the arrays used in this script with some data fetched from a database relating to the particular user. When he selects an entry in the first dropdown menu, he is immediately presented with his relevant data in the second menu, instead of making another request to the server to fetch more data. These types of scripts are very useful when you have to allow a user select some thing from a general level to a more specific level. I mean each successive dropdown menu would be more and more specific choice. Read on to understand the entire thing.


<SCRIPT LANGUAGE = "JavaScript">
<!--

var tennisplayers= new Array("Safin", "Andre Agassi", "Pete Sampras", "Anna Kournikova", "Martina Hingis");
var cricketplayers = new Array("Sachin Tendulkar", "Steve Waugh", "Brian Lara", "Sir Don Bradman");


function set_player() {

 

var select_sport = document.myform.sport;
var select_player = document.myform.player;
var selected_sport = select_sport.options[select_sport.selectedIndex].value;

select_player.options.length=0;
if (selected_sport == "tennis"){

    for(var i=0; i<tennisplayers.length; i++)
    select_player.options[select_player.options.length] = new Option(tennisplayers[i]);
  }
if (selected_sport == "cricket"){
    for(var i=0; i<cricketplayers.length; i++)
      select_player.options[select_player.options.length] = new Option(cricketplayers[i]);
  }

}
-->
</SCRIPT>

<BODY>
<FORM NAME="myform" METHOD="POST">

Sport
<SELECT NAME="sport" onChange="set_player()">
<OPTION VALUE="tennis">-------
<OPTION VALUE="tennis">Tennis
<OPTION VALUE="cricket">Cricket
</SELECT>

Player
<SELECT NAME="player">
<OPTION>------
</SELECT>

</FORM>
</BODY>

In the above script when the user selects either Cricket or Tennis in the first Select Menu, the choices in the second Select Menu automatically changes accordingly.

Try to understand the working of all these scripts properly rather than cut-pasting them. A reference book on Javascript is extremely useful since there are many small details that you got to take note of while scripting else your scripts won't run. Programming in Javascript in conjunction with any other language such as ASP or JSP makes it more tough and you have to take great care about the syntax else you end up in a mess. Thats all..

Hope you enjoyed these 9 examples.



This article has been written by Kiran Pai. All comments and feedback regarding this article may be sent to [email protected]
This article should not be modified in any form.