TweetFollow Us on Twitter

Javascript Intro
Volume Number:12
Issue Number:7
Column Tag:Javatech™

Getting the Jump on JavaScript

Start learning to add life to your Web pages

By Kevin M. Savetz

Note: Source code files accompanying article are located on MacTech CD-ROM or source code disks.

Static Web pages are a dying breed. Although not obsolete yet, it may be one day soon that a Web page that doesn’t do anything just won’t get a second glance. Once upon a time, all Web pages were static. CGI programs started to change that by allowing powerful searches of Web pages, sites that modified themselves based on the time of day or the phase of the moon, and even interactive games. Java, a powerful programming language, is bringing a whole new level of interactivity to the Web. Somewhere in the middle is JavaScript, a new language that’s simple enough for beginning programmers to learn, but powerful enough to interact with Web pages and Java applets in ways previously not possible with any language.

JavaScript is a fledgling language. As I write this, JavaScript isn’t even complete. The technical specifications of the language have been agreed upon, but no Web browsers completely support JavaScript. (JavaScript 3.0, which should incorporate the functions that are currently lacking, is due out in June, give or take a month; no firm date had been set at press time.) But that doesn’t mean that no one is using it; bleeding-edge Web hackers have been experimenting with the crippled JavaScript for months, and many are impressed with what they see.

What is JavaScript?

Java and JavaScript are distinct languages, with different purposes and features. JavaScript was designed to provide an easy way for Web authors to create interactive Web pages. Java is a programming language which is used to create stand-alone applications, called applets. Unlike Java, which is meant for experienced programmers with an understanding of C++, JavaScript is a simpler “scripting” language (like dBASE and AppleScript) aimed at those with less programming experience.

Both are powerful languages, but they each offer distinct functionalities. According to Andy Augustine, vice president of technology for Frequency Graphics, a Web development and hosting service provider, “JavaScript is aimed at the people who don’t have C++ experience, people who don’t have much experience with CGI, but want to create some sort of interactive Web page.”

“Contrary to popular misconceptions, JavaScript was not meant to be a scaled-down version of Java, nor was it intended to be a replacement for CGI (server-side) scripts. Instead, JavaScript functions as an outstanding way to enhance both,” he said.

JavaScript can be used to manage user input as well as to show text, play sounds, display images, or communicate with a plug-in in response to “events” such as a mouse-click or exiting or entering a Web page.

JavaScript’s syntax is loosely based on the Java language, but those who have used both languages say the similarity is very loose indeed. In fact, the closest resemblance the two languages have is their names. JavaScript was originally called Mocha while being developed at Netscape. It was later dubbed LiveScript, and when Netscape Communications partnered with Sun to develop Java, LiveScript was renamed JavaScript.

Java vs. JavaScript

JavaScript programs are interpreted and run entirely on the client side. This means fewer hits and less processing time on the server than with Java (where applets are compiled on the server before being executed on the client) or CGI (which requires the server to do the work and rack up hits).

There are other differences between the two languages. In Java, applets are files distinct from HTML pages; with JavaScript, the code is integrated into the HTML using special tags. (This can cause problems with some Web browsers that do not properly handle JavaScript code.) Like Java, JavaScript is a cross-platform language that can work with any compatible browser.

Here’s an example HTML file with an embedded JavaScript. Between the <BODY> tags, the Web browser displays a form with a space to enter a number. When the user enters a number in the field, the browser starts the script, located between the <SCRIPT> tags. The script itself makes sure the user really entered a number, and displays a dialog box if the user didn’t keep the number within pre-defined limits.

<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--- these comments should hide the script from old browsers
function checkNum(str, min, max) {
 if (str == "") {
 alert("Enter a number in the field, please.")
 return false
 }
 for (var i = 0; i < str.length; i++) {
 var ch = str.substring(i, i + 1)
 if (ch < "0" || ch > "9") {
 alert("Enter a number, please.")
 return false
 }
 }

 var val = parseInt(str, 10)
 if ((val < min) || (val > max)) {
 alert("Try a number from 1 to 10.")
 return false
 }
 return true
}

function thanks() {
 alert("Thank you.")
}
// end hiding from old browsers -->
</SCRIPT>
</HEAD>

<BODY>
<FORM NAME="ex5">
Please enter a number from 1 to 10:
<INPUT NAME="num"
 onChange="if (!checkNum(this.value, 1, 10))
 {this.focus();this.select();} else {thanks()}">
</FORM>
</BODY>

All this only takes one hit on the server - to download the HTML code and the embedded script. Doing this with a CGI script would require multiple hits on the server, once for the HTML file, and again to verify the input every time the user types into the form. JavaScript allows the client to perform more significant calculations without weighing down the server.

Other differences are more technical. JavaScript is object-based: its code uses built-in, extensible objects, but unlike Java, there are no classes or object inheritance. In JavaScript, object references are checked at run-time; in Java, object references must exist upon compilation. In JavaScript, variable data types are not declared, unlike in Java, where they must be declared before use.

Which language is better? Until a JavaScript interpreter is complete, there is no fair comparison. Although it was originally intended as a tool for fledgling programmers, even experienced programmers who know Java will find JavaScript useful. The languages can work together to complement each other.

Currently, the only Web browser with any support for JavaScript is Netscape 2.0, and it lacks much of the functionality promised for the final release. More than 30 other companies, including Microsoft, have agreed to include support for JavaScript in their Web browsers. With the current version of JavaScript, you can send information to the browser (such as a dialog box) and get the status of objects (such as mouse movements), but some of the most exciting functions, such as the abilities to read input streams from documents and to interact with Java applets, are still unimplemented.

When JavaScript includes all of the tools the specs say will be included, including something called the “applet object” (which will allow scripts to interact with Java applets), the two languages will be a mighty team. “As soon as the applet object is released, you will be able to control Java applets with JavaScript, and that will make them work perfectly together,” Augustine says. This means that you will be able to control a Java applet using a Web-based form, with a JavaScript doing the behind-the-scenes translation between the Web page and the applet. The user will be able to use a radio button to select how a Java applet will run - for instance, changing the color and speed of a rotating logo. JavaScript will pass information from the form to the Java applet. JavaScript’s applet object will also allow scripts to send information to and get information from other scripts and CGI programs.

Another tool that will be available in the final release of JavaScript is the “history object”, which will allow the script to see what Web pages the user has recently visited (although to protect the user’s privacy, the script will not be able to share that information with the server). This would allow a page to offer an intelligent “back” button, letting the user move quickly back to any previously visited Web page.

As with Java, security in JavaScript is likely to be an ongoing battle. Several security problems were quickly discovered in JavaScript 2, including a bug that let JavaScript send a blank electronic mail message to someone without the sender’s knowledge. Another bug allowed JavaScript to get a listing of files on the user’s hard drive (although the script could not read the contents of any files).

Now or Later?

Should you bother learning JavaScript now, or is it currently just a toy for experimenters? Should you wait until the final version of the JavaScript interpreter ships before trying to learn the ins and outs of the language? Augustine thinks that now is the time to get a jump start on JavaScripting. “Learn JavaScript right now if you want to capture the market while it is viable; you’ll be ahead of the field. If you wait until it is fully functional before you learn it, I think you’ll be behind the game,” he says. Online tutorials can get you started with the basics of the language, and Internet mailing lists and newsgroups devoted to the topic are already home to thriving communities of developers and experimenters.

Will the serious Web page developer need to understand both Java and JavaScript? Because JavaScript can interact directly with the user anywhere on a Web page (rather than being limited to a single window, as with Java), most Java developers will probably want to learn both. But JavaScript should also be viable as a stand-alone tool for less experienced programmers who want to add interactivity to their Web pages.

Example Scripts

There are already dozens of example JavaScripts on the Web. Many, such as the 1040EZ tax form and body mass calculator, simply compute values input from an HTML form. Others are more inspired, such as the currency exchange calculator, which lets you select two countries from a list and then computes the


exchange rate. I am particularly fond of the Zen koan generator, even though it occasionally causes Netscape 2.0 to crash.

http://www.homepages.com/fun/1040EZ.html

http://www.iohk.com/UserPages/acheng/javascript.html

http://www.superprism.net/doc/EXPRESS/util/currency.html

http://www.wrldpwr.com/javascriptzen.html

The color picker shows how JavaScript can work with frames and color: pass the mouse over the name of a color in one frame and the background of another frame will become that color. Other examples are downright inspirational, such as the JavaScript VRML clock, which uses JavaScript to display a three-dimensional clock if you have a VRML browser.

http://www.lsi.usp.br/doc/color/picker.html

http://www.phoenix.net/~jalonso/applets/vrml

Many more example applications are available at http://www.gamelan.com/.

Remember how interesting (and sometimes annoyingly funky) Web pages became when authors started using and abusing sundry new tools like backgrounds and frames? Expect to see another round of enlightening and obscure Web sites as developers and hackers begin to understand and use JavaScript.

For More Information

A growing number of information sources about JavaScript are online. Andy Augustine’s JavaScript FAQ is at:

http://www.freqgrafx.com/411/jsfaq.html

There is also a JavaScript mailing list, a high-volume, sometimes technical list for discussion about using the language. To subscribe, send a message to majordomo@obscure.org with a message body of “subscribe javascript”. A digest version of the list is also available. To subscribe, use a message body of “subscribe javascript-digest”. Further discussion takes place on the newsgroup comp.lang.javascript.

Netscape’s official JavaScript documentation is required reading if you plan to learn your way around JavaScript. The files are also downloadable for reading offline.

http://home.netscape.com/eng/mozilla/2.0/handbook/javascript/index.html

http://home.netscape.com/eng/mozilla/2.0/handbook/javascript/jsdoc.zip

Augustine maintains a list of online tutorials, example applications and other information at JavaScript 411. Finally, the ubiquitous Yahoo naturally has an index of JavaScript-related goodies.

http://www.freqgrafx.com/411/

http://www.yahoo.com/Computers_and_Internet/Languages/JavaScript/

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »

Price Scanner via MacPrices.net

AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more

Jobs Board

Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.