eBORcOM

Web Development Resources

Simple JavaScript Scripts

This tutorial is part of the Web Development Resources collection.

It is taken from Reaz Hoque's forthcoming book, Practical JavaScript Programming, published by MIS Press.

Practical JavaScript Programming


Since Microsoft introduced Internet Explorer 3.0, JavaScript has gained a quite a bit of recognition. The reason being? Well, now JavaScript is supported by the most popular browsers on the web: Netscape Navigator 2.0+ and Microsoft Explorer 3.0 (aka IE3.0). If you have some knowledge of this easy to learn but powerful scripting language, I would like to encourage you to try some of the simple JavaScript snippets from this article.

In the article, I will show you some neat little scripts that you can use in your web pages and really surprise others who are not familiar with this language. Some of the examples presented here will be useful as well. For example, Now that we have different versions of the Netscape browser and only the latest can handle certain plug-ins or JavaScript syntax, you might want to know which version of the browser your visitor is using. If your visitor is using Navigator 2.0 and you have JavaScript 1.1 on your page, the client's browser surely will crash. Detecting a browser is a great example for making sure that you can offer your page to all of your clients, not just the ones who have the latest browser.

Another example would be displaying the latest update date of your Web page. If your visitor knows when your page was updated, they can choose whether or not to surf the page. Who likes to browse through month-old information?

The same concept will apply to some of the other scripts that are presented here. Just by cutting and pasting some of this code, you can make your site a better looking and more enjoyable place to visit.



Your first JavaScript script

In any language, the programmer needs to find out how to output text into a document. In order to output text in JavaScript you must use write() or writeln(). Here's an example:
<HTML>
<HEAD>
<TITLE>Writing text on a document</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!-- Hiding the code document.write("Welcome to Applications in JavaScript!");
// done hiding -->
</SCRIPT>
</BODY>
</HTML>

Test This Example

If you're familiar with JavaScript syntax, this script should be easy for you to understand. You will notice that we have included the code in between <SCRIPT> and </SCRIPT> tags. We made sure the document object write is in lowercase as JavaScript is case sensitive.

Now, you might be wondering what the difference is between write and writeln. Well, while write just outputs a text, writeln outputs a line feed after the text output.


Date and time

You probably have seen many Web sites that incorporate a clock. Before JavaScript, you had to use CGI to have the current date and time on a page. Now, creating clocks and the date is easy and can make your site look cool. Using this example, you also can create custom greetings for your visitor, depending on the time of day. For example, you can have a message saying, "It's 12:00 a.m.! Go to bed!"

If you look at the Netscape's JavaScript documentation, you will know that there are two built-in functions in JavaScript that let you display date and time. The following example will display the current time and date in a text box with an option to stop the time:

<HTML>
<HEAD>
<TITLE>Showing date and time on a document</TITLE>
<SCRIPT LANGUAGE="JAVASCRIPT">
<!--Hiding the code
var show_time=false;
var timerID=null;

function stop(){
   if (show_time){
       clearTimeout(timerID);
       document.clock.date_time.value=" ";
   }
   show_time=false;
}

function start(form){
   var today=new Date();
   var display_value =" Time= " + today.getHours()
   if(today.getMinutes() < 10){ 
      display_value+=":0" + today.getMinutes();
   }
   else{
      display_value+=":" + today.getMinutes();
   }
   if (today.getSeconds() < 10){
      display_value+=":0" + today.getSeconds();
   }
   else{
      display_value+=":" + today.getSeconds();
   }
   if(today.getHours()>=12){
      display_value+=" P.M." 
      /* Here we have a variable called mygreeting where 
         you can store somthing like this:   
         mygreeting ="Good Morning!"; */
   }
   else{
      display_value+=" A.M."
      /* Now set mygreeting to: 
         mygreeting ="Good Afternoon!"; */
   } 
   display_value += " Date= " + (today.getMonth()+1) + "/"  +
      today.getDate() + "/" + today.getYear();
      document.clock.date_time.value=display_value;
      timerID=setTimeout("start()",100);
      show_time=true;
      /* Here have an alert() method do the following: 
         alert(mygreeting); */
}
//done hiding-->
</SCRIPT>
</HEAD>
<BODY BGCOLOR=white Text=Red Link=Green onLoad=stop()>
<center>
<H1>Displaying Date and Time</H2>
<FORM name=clock>
<INPUT type="text" name="date_time" size=35 value=""><br>
<INPUT type="button" name="show_now" value="Display" onClick=start()>
<INPUT type="button" name="clear_now" value=" Clear " onClick=stop()>
</center>
</FORM>
</BODY>
</HTML>
Test This Example

In this script, we have two functions (stop() and start()) for our two buttons Display and Clear. When the button Display is pressed, the start() function is called, and when the button Clear is pressed, the stop() function is called. Both of these functions are called using the onClick event handler.

Now the stop() function simply clears the setTimeout method that is used in the start() function. This function also clears the text box that displays the time and date. Finally, the function puts a false value to the Boolean variable show_time.

In start() function, a new instance of date using the statement new is created. Then a variable display_value was defined so that we can export the date and time value in the text box later. Remember that we are using the display_value as a string variable. Now we have to make sure that if the seconds and minutes are less than 10, they are both displayed as single digits. The if...else statement is used for that purpose.

In order to display a.m. or p.m., another if...else statement is used to check for a value more than or equal to 12. So, if the time value is more than 12, display_value would then hold "p.m.," otherwise it would hold "a.m." Lastly, the value of the day, month, and the year is added in the variable. Now it's time to display the data into the text box. This is done with the following code:

 document.clock.date_time.value=display_value;
The above code takes the value of display_value and puts it in the property called value of the text box named date_time. The word document is used to insure that we are indicating the current document. Lastly, the variable timerID is set and show_time is set to true. Notice that timeID uses the setTimeOut() function with the parameters start() and 100. The reason why 100 is passed in is because the function start() is within one tenth of the second.

Displaying automatic page update information

Let's say you have a homepage and you update it frequently. Wouldn't it be nice to include the last update date on your page? Well, here is how you can do that:
<HTML>
<HEAD>
<TITLE>Displaying Update Info</TITLE>
</HEAD>
<BODY bgcolor=ffffff>
<script language="JavaScript">
<!--hide script from old browsers
document.write("<h2>This page has been updated: " +
document.lastModified + "</h2>");
// end hiding -->
</script>
</BODY>
</HTML>
Test This Example

All you needed to do here is use the lastModified property of the document. That's all!


Measuring users' time on a page

This script can tell the visitors of your homepage how much time they have spent on your page. To do that, first we create a function called person_in(). This function creates a new date instance which is called via the onLoad() event handler. We then create another function called person_out() which is called via onUnload() event handler. This function also creates a new date instance. We then take the difference of the two date instances, divide the result by 1000, and round the result. The reason to divide the result by 1000 is to convert the visited time into seconds. The result is then displayed via an alert() method.
<HTML>
<HEAD>
<TITLE>Detecting User's Time on a Page</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function person_in() {
   enter=new Date();
}
function person_out() {
   exit=new Date();
   time_dif=(exit.getTime()-enter.getTime())/1000;
   time_dif=Math.round(time_dif);
   alert ("You've only been here for: " + time_dif + " seconds!!")
}
</SCRIPT>
</HEAD>
<BODY bgcolor=ffffff onLoad='person_in()' onUnLoad='person_out()'>
</BODY>
</HTML> 
Test This Example

Detecting a particular browser

Our next example shows you how to detect a particular browser. As mentioned earlier, this is useful because you could have a page that supports JavaScript for only Netscape 3.0, therefore, you don't want a visitor to visit the page without that browser.
<HTML>
<TITLE>Detecting User's Browser</TITLE>
<HEAD></HEAD>
<BODY BGCOLOR=ffffff>
<SCRIPT Language="JavaScript">
if (navigator.appName == "Netscape"){
   if (navigator.appVersion.substring(0, 3) == "3.0"){ 
      if (navigator.appVersion.substring(3, 4) == "b"){
         alert('You are using :' + navigator.appName + ' (' +
         navigator.appCodeName + ') ' + navigator.appVersion + 
            '\nSorry! You are not using Netscape 3.0+');
         history.back();
      }
   }
}
else {
     alert('Sorry! You are not using Netscape 3.0+');
  }
</SCRIPT>
</BODY>
</HTML>
Test This Example

Here we use the some of the properties of the Navigator object. First we find out if the browser is a Netscape browser. If so, we detect if the version is 3.0. If the version is a beta version, we display the whole browser information with its platform, and alert the user that he or she is not using a Netscape 3.0 browser.

Notice that before we closed the if statement, we used the history.back() statement. It is used so that when the user presses OK on the alert message box, the document automatically takes the user to the previous page. This is useful because sometimes if you run JavaScript 1.1 on Netscape browser 2.0 or earlier, the browser might crash; this will prevent users from crashing their browsers.

Here's another useful tip: You could also send the user to a different page if the browser is not Version 3.0. Instead of the history.back() statement, you need to type the following statement: window.location="myotherpage.html".

This script can also alert visitors that if they want to view this page, they need to acquire the appropriate browser.

Warning: The else statement is not effective unless you use a JavaScript-enabled browser besides Netscape, such as Microsoft's Explorer 3.0.


Playing on-demand sound

A page with sound can be really nice! This not only gives users something to listen to when they are visiting, it also makes your site more multimedia savvy. With JavaScript, you can play sound when the document is loaded or exited, or when the user pushes a link. The following listing will show you how we can use an image as a link for playing an on-demand sound.
<HTML>
<HEAD>
<TITLE>Playing on-demand sound</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function play(){
   window.location = "sample.au"
}
</SCRIPT>
</HEAD>
<body bgcolor=ffffff>
<h2>Playing on-demand sound:</h2>
<b>Please click on the image below</b><br>
<a href="ex5_:play()"><img src="sound.jpg" border=0></a>
</body>
</HTML>
Test This Example

First we had an image that calls the function play(). Notice the way we linked the function: javascript:play(). This makes sure that this hyperlink is a JavaScript link that should call the function play(). The play function uses the location property of the document object and simply points to the sound file.

You should note that if you want to play other files such as a Shockwave file, all you need to do is replace the "sample.au" with a shock wave file (e.g."sample.dcr").


Scrolling Banner

The next example will show you how to create a scrolling banner that will display your text on the browser's status bar. This is a useful script as it can display a scrolling message you might want your visitors to see. A banner can grab your visitor's attention and thus is a great way to pass on your information.

The difference between this scrolling banner and others you have seen is that you can control the banner's speed and pause the scrolling. Let's see the script:

<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">

var b_speed=8;   //defines banner speed
var banner_id=10; 
var b_pause=0;   //to pause the banner
var b_pos=0;

function stop() {
   if(!b_pause) {
      clearTimeout(banner_id);
      b_pause=1;
   }
   else {
      banner_main();
      b_pause=0; 
   } 
}

function banner_main() {
   msg="W e l c o m e  to  J a v a S c r i pt!"
      +"  JavaScript can do some really"
      +"  Cool stuff.  Check out http://rhoque.com"
      +" for more examples..."
    	  
   var k=(40/msg.length)+1;
   for(var j=0;j<=k;j++) msg+="     "+msg;
      window.status=msg.substring(b_pos,b_pos+120);
      if(b_pos++==msg.length){	 
         b_pos=0;
      }

   banner_id=setTimeout("banner_main()",1000/b_speed);
}


</script>
</head>

<TITLE>Banner</TITLE>
</HEAD><BODY BGCOLOR="ffffff">
<H1> Example 5.8:</h2>
<P ALIGN=Center>
<FORM name="form1" action="">
<P ALIGN=Center>
<input type="button" value="Start"
onclick='{
   clearTimeout(banner_id);
   b_pos=0;
   banner_main()
   }'>
<input type="button" value="Slower" onclick='
{
   if (b_speed<3){
      alert("Does not get any slower!");
   }
   else b_speed=b_speed-1;
}'>
<input type="button" value="Faster" onclick='
{
   if (b_speed>18){
      alert("Does not get any faster!");
   }
   else b_speed=b_speed+2;
}'>
<input type="button" value="Pause" onclick='stop()'>
<input type="button" value="Reset" onclick='b_speed=8;'>
</FORM>
</BODY>
</HTML>
Test This Example

The script is simple. There are three to four imported parts to the script. There are two functions: stop() and banner_main(). The stop() function is used to pause the scrolling text. First we check if the banner is paused, if it is not, we use the clearTimeout() method to pause the banner and make the b_pause variable true. When the user clicks on the Pause button, the function calls the banner_main() function. Lastly, we make the b_pause variable false.

In our banner_main() function, we first assign a value to the variable msg. Then, we take the length of msg, divide that by 40, and add one to the result. This value is assigned to k. Now a loop is used from j to k to add the blanks to the value of msg. Next, we display the banner in a window's status bar by taking the substring of msg from 0 to 120. Later we see if the b_pos becomes as long as the msg length and set the b_pos equal to zero again.

To make the banner go faster we just increase the value of b_speed, and to make the banner go slower we decrease the value of b_speed.


Internet Link Exchange


eBORcOM
Brought to you by eBORcOM