TweetFollow Us on Twitter

What is JavaScript?

Volume Number: 14 (1998)
Issue Number: 5
Column Tag: Scripting

What is JavaScript?

by Dori Smith

As these examples show, it's just a simple web scripting language

Introduction

What's JavaScript? What's the difference between JavaScript and Java? Isn't JavaScript just a simplified version of Java? These are common questions that I get all the time.

Netscape originally invented a simple scripting language called LiveScript, which was to be a proprietary add-on to HTML. When Sun's new language Java became unexpectedly popular, Netscape was quick to jump on the Java bandwagon, and re-christened their scripting language JavaScript. Outside of the first four letters, there are almost no other similarities between the two.

Microsoft then added their own version of JavaScript to Internet Explorer, which they named JScript. Unfortunately, the two were not identical, so Netscape then attempted to straighten matters out by turning JavaScript over to ECMA, a Switzerland-based standards body. This gave three main versions of JavaScript-based languages: JavaScript, which works primarily with Netscape's browsers, JScript, which works with Internet Explorer, and ECMAScript, with which no browser is completely compatible. Netscape and Microsoft have both stated that future versions will match the ECMAScript standard, which should lead to convergence. However, as the most-used features are common to all, compatibility is not an issue unless you are trying to use JavaScript to control DHTML.

JavaScript is growing in popularity due to its simple learning curve relative to the amount of power it provides. Complete non-programmers are able to add a little bit of interactivity to their web pages without buying an IDE or sweating over why a program won't compile. There are numerous Web sites which contain any number of scripts available for the taking, and Netscape has fairly complete documentation on their site. And of course, there's the always useful ability to view the source of Web pages.

Syntax & Basics

The syntax of JavaScript will be simple to anyone who has ever programmed in an object oriented language. The primary object is the window, which is at the top of the hierarchy. Under that are the document, frame, location, history, and navigator objects. In turn, the document object contains anchors, applets, embeds, forms, images, and links, each of which is an array of objects. So, a reference to the first image on a page would be to self.document.image[0], although it is preferable to use names instead of numbers for clarity.

JavaScript is not a stand-alone language, but rather a scripting add-on to HTML. JavaScript is added to HTML commands by use of the <SCRIPT> tag. Anything within this tag is (or should be) ignored by browsers that do not support JavaScript. JavaScript is the most popular scripting language in use due to its cross-platform and cross-browser support, although VBScript is sometimes used on intranets when the scripter knows that everyone accessing the page is on Windows. JavaScript will attempt to execute the commands within the <SCRIPT> tag if there is no LANGUAGE attribute, or if the LANGUAGE attribute is set to JavaScript; in addition, the LANGUAGE attribute also can be used to distinguish between various versions of JavaScript.

The JavaScript in Listing 1 consists of a single line: document.write("Hello, World!"). This writes the typical "Hello, World" message, using the document.write() method. This method dynamically generates text within HTML files, in lieu of hard-coded HTML. Figure 1 shows the results.

Listing 1: Everyone's first script

hello.html

<HTML>
<HEAD>
   <TITLE>Barely a script at all</TITLE>
</HEAD>
<BODY BGCOLOR=WHITE>
<H1>
<SCRIPT LANGUAGE="JAVASCRIPT">
      document.write("Hello, World!")
</SCRIPT>
</H1>   
</BODY>
</HTML>

Figure 1. The typical "Hello, World".

Using JavaScript

There are three ways that JavaScript can be used within an HTML file. It can be put within <SCRIPT> tags within the <HEAD> tag (header scripts), within <SCRIPT> tags within the <BODY> tag (body scripts), or called directly when certain events occur.

JavaScript is put inside the <HEAD> tag primarily when you are initializing variables and creating functions that will be used throughout the entire script. Code here is executed once, when the page is loaded. Within the <BODY> tag, the best use of JavaScript is to write out text on-the-fly. JavaScript handles these events:

Event Caused by
onAbort The user aborted loading the page
onBlur The user left the object
onChange The user changed the object
onClick The user clicked on an object
onError The script encountered an error
onFocus The user made an object active
onLoad The object finished loading
onMouseOver The cursor moved over an object
onMouseOut The cursor moved off of an object
onSelect The user selected the contents of an object
onSubmit The user submitted a form
onUnload The user left the window

Any of these event handlers can be added to any HTML tag which can cause the event to occur. For example, the onLoad event handler can be added to the <BODY> tag, and the event will be called when the page has completed loading.

Image Rollovers

One of the most common uses of JavaScript is the image rollover. This is a technique which requires little programming knowledge, but can greatly enhance the experience of visiting a Web site.

HTML has its place, but it's static. A user entering a web site and seeing a window like that in Figure 2 doesn't know what they should do -- are these words links, or just graphics giving us information?

Figure 2. The Navigation Bar, upon entering the page.

Adding a rollover to this gives the look in Figure 3. Now, when a user moves a cursor over any of the options, it becomes clear that this is a navigation bar, and that each of these words is a live link.

Figure 3. When doing a rollover, the arrow gives the user feedback.

Image rollovers are handled by browsers that support JavaScript versions 1.1 and later, which includes Netscape Navigator versions 3 and above, Internet Explorer 4, and some versions of Internet Explorer 3. Listing 2 shows the code to create the image rollover effect.

Listing 2: Image rollovers give users feedback

navbar.html

<HTML>
<HEAD>
   <TITLE>Navbar</TITLE>

   <SCRIPT LANGUAGE="JAVASCRIPT">
      <!-- Hide from old browsers

      if (document.images) {
         productOn = new Image
         pricingOn = new Image
         pressOn = new Image
         
         productOff = new Image
         pricingOff = new Image
         pressOff = new Image
         
         productOn.src = "products_on.gif"
         pricingOn.src = "pricing_on.gif"
         pressOn.src = "press_on.gif"
         
         productOff.src = "products_off.gif"
         pricingOff.src = "pricing_off.gif"
         pressOff.src = "press_off.gif"
      }
      else {
         productOn.src = ""
         pricingOn.src = ""
         pressOn.src = ""
         
         productOff.src = ""
         pricingOff.src = ""
         pressOff.src = ""
         
         document.products = ""
         document.pricing = ""
         document.press = ""
      }
      
      // Stop hiding from old browsers -->
   </SCRIPT>
</HEAD>

<BODY BGCOLOR=WHITE>
   <A HREF="products.html" 
      onMouseOver="products.src=productOn.src" 
      onMouseOut="products.src=productOff.src">
   <IMG src="products_off.gif" WIDTH="226" HEIGHT="37" 
      BORDER="0" NAME="products"></A><BR>
      
   <A HREF="pricing.html" 
      onMouseOver="pricing.src=pricingOn.src" 
      onMouseOut="pricing.src=pricingOff.src">
   <IMG src="pricing_off.gif" WIDTH="189" HEIGHT="80" 
      BORDER="0" NAME="pricing"></A><BR>
      
   <A HREF="press.html" 
      onMouseOver="press.src=pressOn.src" 
      onMouseOut="press.src=pressOff.src">
   <IMG src="press_off.gif" WIDTH="154" HEIGHT="36" 
      BORDER="0" NAME="press"></A>
</BODY>
</HTML>

In the <HEAD> tag, we do our initializations. The first thing needed is to hide the JavaScript commands from browsers that are too old to understand JavaScript and too old to understand that they're supposed to ignore text within tags they can't handle. This is done by starting a HTML comment, which is not closed until just before the closing script tag. This closing comment line works because it starts with a JavaScript comment symbol, which causes JavaScript to ignore it. Next, we check to see if the browser we're using supports manipulation of image objects. If it doesn't, then care must be taken to avoid giving the user errors. This is done by checking for the existence of document.images. If it exists, we're able to do the rollover. If it doesn't, they have an old browser (JavaScript 1.0) or they have JavaScript turned off.

The image rollover technique requires two versions of each image: one "on" and one "off," based on whether the cursor is or isn't on top of the image. So, for each of the three images in the window, we need to create 2 new image objects. We then assign an image URL to each of these image objects, by setting their src property. This both enables the variables to be referenced by name later within the body, and pre-loads the graphics into the browser cache, so that they appear virtually immediately when the cursor moves over the image.

We also give each image on the page a name, by setting the NAME attribute of each within the <IMG> tag. While images can be referred to as document.image[0] (for instance), it is more flexible & manageable to instead refer to document.products. This allows us to refer to the image by name later when we want to manipulate it.

If the user has a browser that does not support image manipulation, we must initialize the same variables, so that using them later does not cause an error. Consequently, we set the src of each to the empty string. In addition, we set three other variables: document.products, document.pricing, and document.press. Older browsers don't understand that images can have names, so simply defining them here lets us use the objects in all browsers without an error.

Within the body, we add event handlers to the link tags around the images, for both onMouseOver and onMouseOut. For example, when the products image first loads, it displays the image products_off.gif. When the cursor goes over the image, the src of products is reset to the src of the productOn image that we set in the header script. This displays the version of the image with an arrow. When the cursor is moved off the image area, the src of products is reset to the src of the productOff image (set in the header script).

If the browser does not support image manipulation, the onMouseOver event instead just sets the src of an empty string to the src of another empty string, with no errors and no effect.

The secret to having this look good is proper preparation of the images, avoiding the two most common mistakes. Firstly, the two images must be of identical sizes. When one replaces the other, the size of the image area doesn't change, even though the images themselves may be of different sizes. Instead, the browser will automatically resize the graphics for you, with unpredictable (and virtually always unpleasant) results. Figure 4 shows the six images actually used in this example. The "off" versions of the images, although they do not include the red arrow, have identical dimensions to their "on" versions. Secondly, the images must not have transparent areas. In this case, if the white areas were transparent, the images would look fine upon first loading, and would also look fine when the cursor was moved over them. But, when the cursor was moved off the first time, the red arrow would continue to show through the transparent area of the "off" image.

Figure 4. There are actually 6 images; 1 each with and without the arrow.

JavaScript Navigation

Another way of improving the user interface of a web site is to improve its navigation. One technique of doing this is to create a jumping popup menu, such as the ones on Apple's DevWorld site. This example requires little actual scripting, outside of handling the onChange event from the popup menu, combined with some knowledge of how JavaScript interacts with HTML.

The HTML <SELECT> is used to create the popup menu shown in Figure 5. It has four options: "Pick an area," "Products," "Pricing," and "Press." Choosing an option triggers the onChange event, which evaluates the line of JavaScript shown in Listing 3.

Figure 5. This popup menu sends you to a new page instantly.

Listing 3: Instant navigation with a popup menu

popup.html

<HTML>
   <HEAD>
      <TITLE>Pop-up Menu</TITLE>
   </HEAD>
   <BODY BGCOLOR=WHITE>
      <P>Where do you want to go?</P>
      <FORM>
      <SELECT 
         onChange="if (this.selectedIndex > 0)
window.location.href=this.options[this.selectedIndex].value">
         <OPTION>Pick an area
         <OPTION VALUE="products.html">Products
         <OPTION VALUE="pricing.html">Pricing
         <OPTION VALUE="press.html">Press
      </SELECT>
      </FORM>
   </BODY>
</HTML>

Firstly, we check the value of selectedIndex. This is a number between 0 and 3, depending on which option was chosen. If the option chosen was the first ("Pick an area"), we don't want to do anything, so we only do anything if this.selectedIndex is greater than zero.

Otherwise, changing the value of window.location.href will force the browser to load a new page. This example uses the HTML VALUE attribute of <OPTION> to store the new page that we want to jump to. Each of these values can be referenced by JavaScript via the value property of the options array. When the user chooses an option, JavaScript finds the new page by referencing into the options array with the selectedIndex, and using its value as the location of the page.

One of the major benefits of this style of handling popup menus is that changes to the menu can be made with no knowledge of JavaScript necessary. In fact, once the onChange handler has been added, the page can then be modified by WYSIWYG editors with no loss in functionality, so long as the VALUE attributes are maintained correctly.

There's one small trick here: if you decide to change the popup so that the first option on the menu is a valid location, the user won't be able to ever get there. The event handled is onChange, and there's no way for a user to cause it to be triggered when choosing the default option.

Flow Control

Like most programming languages, JavaScript has the expected ways of controlling the flow of commands. Listing 4 and Figure 6 demonstrate functions, loops, and if statements in JavaScript.

Listing 4: Controlling flow in JavaScript

factorial.html

<HTML>
<HEAD>
   <TITLE>Factorial</TITLE>

   <SCRIPT LANGUAGE="JAVASCRIPT">
      <!-- Hide script from old browsers
      
      function showFactorial(theEntry) {
         document.myForm.result.value =
            calcFactorial(theEntry.value)
      }
   
      function calcFactorial(inVal) {
         if (isNaN(inVal))                // isNan = Is Not a Number
            return("Not a number")
         
         startVal = eval(inVal)          // eval turns a string into a number
         if (startVal < 0 || startVal != Math.floor(startVal))
            return ("Invalid number")

         endVal = 1
         for (i=1; i<=startVal; i++) {
            endVal = endVal * i
         }
         return(endVal)
      }
   
      // End hiding script from old browsers -->
   </SCRIPT>

</HEAD>
<BODY BGCOLOR=WHITE>

   <H3>The factorial of
   <FORM NAME="myForm">
      <INPUT TYPE=TEXT SIZE=3
         onChange="javascript:showFactorial(this)"> is
   <INPUT TYPE=TEXT NAME="result">
   </FORM>
   </H3>
</BODY>
</HTML>

In this example, the user enters a number in the first field. Changing this field passes control to the onChange event handler, which calls the showFactorial() function, with the entry field as its parameter. The showFactorial() function calls the calcFactorial() function, passing it the value of the entry field.

The calcFactorial() function returns either an error message (if not a number, less than zero, or not an integer) or the factorial to its caller. When control passes back to showFactorial(), the result is put into the result field in the browser window.

Figure 6. Entering a number displays its factorial.

Conclusion

Another popular use of JavaScript is form validation, which will tell the user if the form they've submitted is valid without having the overhead of connecting to a Web server. This technique gives the user the impression of speedy Web access, when they haven't accessed your server at all.

JavaScript is growing in popularity, due to many factors, including its ease of learning, the growing share of JavaScript-enabled browsers, and the large number of resources available to novices. With Dynamic HTML on the horizon, JavaScript will become more important and more prevalent in the future.

Bibliography & Suggested Reading

  • Castro, Elizabeth. HTML for the World Wide Web., Visual QuickStart Guide. 2nd edn. Peachpit Press, 1997.
  • Flanagan, David. JavaScript: The Definitive Guide. 2nd edn. O'Reilly & Associates, 1997.
  • Negrino, Tom and Dori Smith. JavaScript for the World Wide Web, Visual QuickStart Guide,. 2nd edn. Peachpit Press, 1998.

Internet References


Dori Smith, dori@chalcedony.com, is a partner at Chalcedony Consulting, and is the co-author (with Tom Negrino) of JavaScript for the World Wide Web, Visual QuickStart Guide, 2nd Edition (Peachpit Press, 1998).

 
AAPL
$112.65
Apple Inc.
+3.24
MSFT
$47.52
Microsoft Corpora
+1.78
GOOG
$511.10
Google Inc.
+6.21

MacTech Search:
Community Search:

Software Updates via MacUpdate

Mellel 3.3.7 - Powerful word processor w...
Mellel is the leading word processor for OS X and has been widely considered the industry standard since its inception. Mellel focuses on writers and scholars for technical writing and multilingual... Read more
ScreenFlow 5.0.1 - Create screen recordi...
Save 10% with the exclusive MacUpdate coupon code: AFMacUpdate10 Buy now! ScreenFlow is powerful, easy-to-use screencasting software for the Mac. With ScreenFlow you can record the contents of your... Read more
Simon 4.0 - Monitor changes and crashes...
Simon monitors websites and alerts you of crashes and changes. Select pages to monitor, choose your alert options, and customize your settings. Simon does the rest. Keep a watchful eye on your... Read more
BBEdit 11.0.2 - Powerful text and HTML e...
BBEdit is the leading professional HTML and text editor for the Mac. Specifically crafted in response to the needs of Web authors and software developers, this award-winning product provides a... Read more
ExpanDrive 4.2.1 - Access cloud storage...
ExpanDrive builds cloud storage in every application, acts just like a USB drive plugged into your Mac. With ExpanDrive, you can securely access any remote file server directly from the Finder or... Read more
Adobe After Effects CC 2014 13.2 - Creat...
After Effects CC 2014 is available as part of Adobe Creative Cloud for as little as $19.99/month (or $9.99/month if you're a previous After Effects customer). After Effects CS6 is still available... Read more
Command-C 1.1.7 - Clipboard sharing tool...
Command-C is a revolutionary app which makes easy to share your clipboard between iOS and OS X using your local WiFi network, even if the app is not currently opened. Copy anything (text, pictures,... Read more
Tidy Up 4.0.2 - Find duplicate files and...
Tidy Up is a complete duplicate finder and disk-tidiness utility. With Tidy Up you can search for duplicate files and packages by the owner application, content, type, creator, extension, time... Read more
Typinator 6.3 - Speedy and reliable text...
Typinator turbo-charges your typing productivity. Type a little. Typinator does the rest. We've all faced projects that require repetitive typing tasks. With Typinator, you can store commonly used... Read more
GraphicConverter 9.5 - Graphics editor w...
GraphicConverter is an all-purpose image-editing program that can import 200 different graphic-based formats, edit the image, and export it to any of 80 available file formats. The high-end editing... Read more

Latest Forum Discussions

See All

Shift - Photo Filters Designed By You (...
Shift - Photo Filters Designed By You 1.0 Device: iOS Universal Category: Photography Price: $.99, Version: 1.0 (iTunes) Description: | Read more »
Elastic Drums (Music)
Elastic Drums 1.0 Device: iOS iPhone Category: Music Price: $3.99, Version: 1.0 (iTunes) Description: *** Introduction price 3,99$ instead of 7,99$ *** Elastic Drums is a music app with 6 channels of synthesized drum sounds, a step... | Read more »
Fireworks Simulator (Games)
Fireworks Simulator 1.0.8 Device: iOS Universal Category: Games Price: $.99, Version: 1.0.8 (iTunes) Description: *** 50% discount – For a short time only *** You can play Fireworks Simulator on these devices: - iPhone 5, 5s, 5c, 6,... | Read more »
Nicky's Gift (Games)
Nicky's Gift 1.0 Device: iOS Universal Category: Games Price: $.99, Version: 1.0 (iTunes) Description: Everybody! Merry Christmas! There's 48 levels in the game. Let's go! Nicky's Gift | Read more »
The Hit List — Simply Powerful Tasks, To...
The Hit List — Simply Powerful Tasks, To-Dos, Projects, & Reminders 2.0 Device: iOS iPhone Category: Productivity Price: $9.99, Version: 2.0 (iTunes) Description: >> LAUNCH SPECIAL: The Hit List 2 for iPhone is ONLY $9.99... | Read more »
Mahjong Journey Review
Mahjong Journey Review By Jennifer Allen on December 18th, 2014 Our Rating: :: STEADY MATCHINGiPad Only App - Designed for the iPad Aimed at the more laid back gamer, Mahjong Journey isn’t for everyone, but those looking for some... | Read more »
Emoji Type - custom keyboard with predic...
Emoji Type - custom keyboard with predictive emojis 0.4.0 Device: iOS iPhone Category: Utilities Price: $.99, Version: 0.4.0 (iTunes) Description: Emoji Type is custom keyboard for iOS 8 that auto suggests emojis as you type. ABOUT... | Read more »
Game of the Year 2014 – 148Apps Staff Pi...
The end of 2014 is almost here, which can only mean one thing. Okay it can mean a lot of things, but in this specific context it means Game of the Year lists! Which is why the 148Apps staff have all picked their favorites from the past year. And why... | Read more »
UponPixels Review
UponPixels Review By Jennifer Allen on December 18th, 2014 Our Rating: :: CREATIVE TYPOGRAPHYUniversal App - Designed for iPhone and iPad Add cool typography and objects to your photos with the easy to use UponPixels.   | Read more »
The Vikings are Coming! CastleStorm’s Ne...
The Vikings are Coming! CastleStorm’s New Update Adds a Survival Mode Posted by Jessica Fisher on December 18th, 2014 [ permalink ] | Read more »

Price Scanner via MacPrices.net

Save up to $400 on MacBooks with Apple Certif...
The Apple Store has Apple Certified Refurbished 2014 MacBook Pros and MacBook Airs available for up to $400 off the cost of new models. An Apple one-year warranty is included with each model, and... Read more
Save up to $300 on Macs, $30 on iPads with Ap...
Purchase a new Mac or iPad at The Apple Store for Education and take up to $300 off MSRP. All teachers, students, and staff of any educational institution qualify for the discount. Shipping is free,... Read more
iOS and Android OS Targeted by Man-in-the-Mid...
Cloud services security provider Akamai Technologies, Inc. has released, through the company’s Prolexic Security Engineering & Research Team (PLXsert), a new cybersecurity threat advisory. The... Read more
KMI MIDI K-Board Great Gift for Amateur &...
The K-Board is a MIDI Nano keyboard for music creation for iPad, Android, And computers; the easiest way to make music with iPads & Android tablets, and Mac, Windows, or Linux computers. Ultra-... Read more
Amazon offers 15-inch 2.2GHz Retina MacBook P...
 Amazon.com has the 15″ 2.2GHz Retina MacBook Pro on sale for $1699 including free shipping. Their price is $300 off MSRP. Stock is limited, so act now if you’re interested. Read more
Holiday sales continue: MacBook Pros for up t...
 B&H Photo has new MacBook Pros on sale for up to $300 off MSRP as part of their Holiday pricing. Shipping is free, and B&H charges NY sales tax only: - 15″ 2.2GHz Retina MacBook Pro: $1699... Read more
Holiday sale: Mac minis available for up to $...
 B&H Photo has new 2014 Mac minis on sale for up to $80 off MSRP. Shipping is free, and B&H charges NY sales tax only: - 1.4GHz Mac mini: $459 $40 off MSRP - 2.6GHz Mac mini: $629 $70 off... Read more
Google Search App For iOS Gets A Major Makeov...
Google has given iOS users an early Christmas present with a substantial update of it’s not-very-often-upgraded Google Search app. Google Search has been my go-to tool for Web searches since it was... Read more
ShopKeep Apple Pay And Chip Card Reader Avail...
ShopKeep, a cloud-based technology provider to more than 10,000 small business owners to manage retail shops and restaurants with iPads, has released its new Apple Pay and chip card reader. This... Read more
Holiday sale! 27-inch 5K iMac for $2299, save...
 B&H Photo has the 27″ 3.5GHz 5K iMac in stock today and on sale for $2299 including free shipping plus NY sales tax only. Their price is $200 off MSRP, and it’s the lowest price available for... Read more

Jobs Board

Project Manager, *Apple* Financial Services...
**Job Summary** Apple Financial Services (AFS) offers consumers, businesses and educational institutions ways to finance Apple purchases. We work with national and Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.