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

Dropbox 193.4.5594 - Cloud backup and sy...
Dropbox is a file hosting service that provides cloud storage, file synchronization, personal cloud, and client software. It is a modern workspace that allows you to get to all of your files, manage... Read more
Google Chrome 122.0.6261.57 - Modern and...
Google Chrome is a Web browser by Google, created to be a modern platform for Web pages and applications. It utilizes very fast loading of Web pages and has a V8 engine, which is a custom built... Read more
Skype 8.113.0.210 - Voice-over-internet...
Skype is a telecommunications app that provides HD video calls, instant messaging, calling to any phone number or landline, and Skype for Business for productive cooperation on the projects. This... Read more
Tor Browser 13.0.10 - Anonymize Web brow...
Using Tor Browser you can protect yourself against tracking, surveillance, and censorship. Tor was originally designed, implemented, and deployed as a third-generation onion-routing project of the U.... Read more
Deeper 3.0.4 - Enable hidden features in...
Deeper is a personalization utility for macOS which allows you to enable and disable the hidden functions of the Finder, Dock, QuickTime, Safari, iTunes, login window, Spotlight, and many of Apple's... Read more
OnyX 4.5.5 - Maintenance and optimizatio...
OnyX is a multifunction utility that you can use to verify the startup disk and the structure of its system files, to run miscellaneous maintenance and cleaning tasks, to configure parameters in the... Read more
Hopper Disassembler 5.14.1 - Binary disa...
Hopper Disassembler is a binary disassembler, decompiler, and debugger for 32- and 64-bit executables. It will let you disassemble any binary you want, and provide you all the information about its... Read more

Latest Forum Discussions

See All

Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »
Live, Playdate, Live! – The TouchArcade...
In this week’s episode of The TouchArcade Show we kick things off by talking about all the games I splurged on during the recent Playdate Catalog one-year anniversary sale, including the new Lucas Pope jam Mars After Midnight. We haven’t played any... | Read more »
TouchArcade Game of the Week: ‘Vroomies’
So here’s a thing: Vroomies from developer Alex Taber aka Unordered Games is the Game of the Week! Except… Vroomies came out an entire month ago. It wasn’t on my radar until this week, which is why I included it in our weekly new games round-up, but... | Read more »
SwitchArcade Round-Up: ‘MLB The Show 24’...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for March 15th, 2024. We’re closing out the week with a bunch of new games, with Sony’s baseball franchise MLB The Show up to bat yet again. There are several other interesting games to... | Read more »
Steam Deck Weekly: WWE 2K24 and Summerho...
Welcome to this week’s edition of the Steam Deck Weekly. The busy season has begun with games we’ve been looking forward to playing including Dragon’s Dogma 2, Horizon Forbidden West Complete Edition, and also console exclusives like Rise of the... | Read more »
Steam Spring Sale 2024 – The 10 Best Ste...
The Steam Spring Sale 2024 began last night, and while it isn’t as big of a deal as say the Steam Winter Sale, you may as well take advantage of it to save money on some games you were planning to buy. I obviously recommend checking out your own... | Read more »
New ‘SaGa Emerald Beyond’ Gameplay Showc...
Last month, Square Enix posted a Let’s Play video featuring SaGa Localization Director Neil Broadley who showcased the worlds, companions, and more from the upcoming and highly-anticipated RPG SaGa Emerald Beyond. | Read more »
Choose Your Side in the Latest ‘Marvel S...
Last month, Marvel Snap (Free) held its very first “imbalance" event in honor of Valentine’s Day. For a limited time, certain well-known couples were given special boosts when conditions were right. It must have gone over well, because we’ve got a... | Read more »
Warframe welcomes the arrival of a new s...
As a Warframe player one of the best things about it launching on iOS, despite it being arguably the best way to play the game if you have a controller, is that I can now be paid to talk about it. To whit, we are gearing up to receive the first... | Read more »
Apple Arcade Weekly Round-Up: Updates an...
Following the new releases earlier in the month and April 2024’s games being revealed by Apple, this week has seen some notable game updates and events go live for Apple Arcade. What The Golf? has an April Fool’s Day celebration event going live “... | Read more »

Price Scanner via MacPrices.net

Apple Education is offering $100 discounts on...
If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take $100 off the price of a new M3 MacBook Air.... Read more
Apple Watch Ultra 2 with Blood Oxygen feature...
Best Buy is offering Apple Watch Ultra 2 models for $50 off MSRP on their online store this week. Sale prices available for online orders only, in-store prices may vary. Order online, and choose... Read more
New promo at Sams Club: Apple HomePods for $2...
Sams Club has Apple HomePods on sale for $259 through March 31, 2024. Their price is $40 off Apple’s MSRP, and both Space Gray and White colors are available. Sale price is for online orders only, in... Read more
Get Apple’s 2nd generation Apple Pencil for $...
Apple’s Pencil (2nd generation) works with the 12″ iPad Pro (3rd, 4th, 5th, and 6th generation), 11″ iPad Pro (1st, 2nd, 3rd, and 4th generation), iPad Air (4th and 5th generation), and iPad mini (... Read more
10th generation Apple iPads on sale for $100...
Best Buy has Apple’s 10th-generation WiFi iPads back on sale for $100 off MSRP on their online store, starting at only $349. With the discount, Best Buy’s prices are the lowest currently available... Read more
iPad Airs on sale again starting at $449 on B...
Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices again for $150 off Apple’s MSRP, starting at $449. Sale prices for online orders only, in-store price may vary. Order online, and choose... Read more
Best Buy is blowing out clearance 13-inch M1...
Best Buy is blowing out clearance Apple 13″ M1 MacBook Airs this weekend for only $649.99, or $350 off Apple’s original MSRP. Sale prices for online orders only, in-store prices may vary. Order... Read more
Low price alert! You can now get a 13-inch M1...
Walmart has, for the first time, begun offering new Apple MacBooks for sale on their online store, albeit clearance previous-generation models. They now have the 13″ M1 MacBook Air (8GB RAM, 256GB... Read more
Best Apple MacBook deal this weekend: Get the...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New 15-inch M3 MacBook Air (Midnight) on sale...
Amazon has the new 15″ M3 MacBook Air (8GB RAM/256GB SSD/Midnight) in stock and on sale today for $1249.99 including free shipping. Their price is $50 off MSRP, and it’s the lowest price currently... Read more

Jobs Board

Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
Senior Software Engineer - *Apple* Fundamen...
…center of Microsoft's efforts to empower our users to do more. The Apple Fundamentals team focused on defining and improving the end-to-end developer experience in Read more
Relationship Banker *Apple* Valley Main - W...
…Alcohol Policy to learn more. **Company:** WELLS FARGO BANK **Req Number:** R-350696 **Updated:** Mon Mar 11 00:00:00 UTC 2024 **Location:** APPLE VALLEY,California Read more
Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill WellSpan Medical Group, York, PA | Nursing | Nursing Support | FTE: 1 | Regular | Tracking Code: 200555 Apply Now Read more
Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.