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

ffWorks 3.3.5 - A Comprehensive Video Co...
ffWorks, focused on simplicity, brings a fresh approach to the use of FFmpeg, allowing you to create ultra-high-quality movies without the need to write a single line of code on the command-line.... Read more
Arq 7.19.11 - Online backup to Google Dr...
Arq is super-easy online backup for Mac and Windows computers. Back up to your own cloud account (Amazon Cloud Drive, Google Drive, Dropbox, OneDrive, Google Cloud Storage, any S3-compatible server... Read more
Opera 97.0.4719.28 - High-performance We...
Opera is a fast and secure browser trusted by millions of users. With the intuitive interface, Speed Dial and visual bookmarks for organizing favorite sites, news feature with fresh, relevant content... Read more
Google Chrome 111.0.5563.110 - Modern an...
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
Vivaldi 5.7.2921.65 - An advanced browse...
Vivaldi is a browser for our friends. We live in our browsers. Choose one that has the features you need, a style that fits and values you can stand by. From the look and feel, to how you interact... Read more
Ableton Live 11.2.11 - Record music usin...
Ableton Live lets you create and record music on your Mac. Use digital instruments, pre-recorded sounds, and sampled loops to arrange, produce, and perform your music like never before. Ableton Live... Read more
Adobe Acrobat DC 23.001.20093 - Powerful...
Acrobat DC is available only as a part of Adobe Creative Cloud, and can only be installed and/or updated through Adobe's Creative Cloud app. Adobe Acrobat DC DC with Adobe Document Cloud services is... Read more
Adobe Acrobat Reader 23.001.20093 - View...
Adobe Acrobat Reader allows users to view PDF documents. You may not know what a PDF file is, but you've probably come across one at some point. PDF files are used by companies and even the IRS to... Read more
Paragon NTFS 15.10.590 - Provides full r...
Paragon NTFS breaks down the barriers between Windows and macOS. Paragon NTFS effectively solves the communication problems between the Mac system and NTFS. Write, edit, copy, move, delete files on... Read more
Slack 4.31.152 - Collaborative communica...
Slack brings team communication and collaboration into one place so you can get more work done, whether you belong to a large enterprise or a small business. Check off your to-do list and move your... Read more

Latest Forum Discussions

See All

TouchArcade Game of the Week: ‘Well Word...
We were already big fans of developer BJ Malicoat, who does business under the name Bird Cartel, due to the release of Pine Tar Poker late last year. Poker is one of those games that kind of is what it is, so it’s always very hard to come up with... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for March 24th, 2023. It turned out to be a fairly busy one today. We’ve got a little news to look at, plus a review from our pal Mikhail. After that, we get into the many new releases... | Read more »
‘Honkai Star Rail’ Release Date Announce...
Last month, Genshin Impact and Honkai Impact 3rd developer HoYoverse began pre-orders and pre-registrations for the upcoming space fantasy turn-based RPG Honkai Star Rail. | Read more »
Tactical Card Battling RPG ‘Black Book’...
Developer Merteshka and publisher HypeTrain Digital just revealed an iOS version of the card battling tactical RPG Black Book . Black Book is available on PC, Nintendo Switch, Xbox One, and PS4 right now. It will be coming to iOS on April 21st with... | Read more »
Clue/Cluedo: Hasbro’s Mystery Game+ Is T...
Clue: Hasbro’s Mystery Game+ from Marmalade Game Studios is this week’s new Apple Arcade release and it is out now alongside some notable updates. Clue: Hasbro’s Mystery Game+ or Cluedo: Hasbro’s Mystery Game+ depending on your region joins the... | Read more »
‘Stakes Winner ACA NEOGEO’ Review – A Ho...
When it comes to the NEOGEO, a few genres come to mind. Fighting games. Side-scrolling action games. Maybe shooters and beat-em-ups. The usual array of sports. You probably don’t think of horse racing games, but this was an arcade platform that was... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for March 23rd, 2023. In today’s article, we kick things off with a couple of reviews. I take a look at Playism and kouri’s Ib, while our pal Mikhail has a look at the latest DLC... | Read more »
Snowbreak: Containment Zone is the lates...
Mobile gaming enthusiasts will soon be able to get their fill of sci-fi shooting, with Amazing Season announcing their upcoming game, Snowbreak: Containment Zone. Pre-registrations are now open for fans, and we also have their first trailer to get... | Read more »
Square Enix’s Card RPGs Voice of Cards:...
Back in late 2021, Square Enix released a new card-based RPG Voice of Cards: The Isle Dragon Roars on PS4, Nintendo Switch, and PC featuring some of the staff behind the NieR and Drakengard games. This included Yoko Taro, Yosuke Saito, Keiichi Okabe... | Read more »
Out Now: ‘Mighty DOOM’, ‘Down in Bermuda...
Each and every day new mobile games are hitting the App Store, and so each week we put together a big old list of all the best new releases of the past seven days. Back in the day the App Store would showcase the same games for a week, and then... | Read more »

Price Scanner via MacPrices.net

Shop our Apple MacBook Price Trackers for the...
We’ve updated our Apple award-winning MacBook Price Trackers with the latest information on prices, bundles, and availability for 16″, 14″, and 13″ MacBook Pros along with 13″ MacBook Airs from Apple... Read more
Back in stock: M1-powered Mac minis for only...
Apple has restocked clearance M1-powered Mac minis in their Certified Refurbished section starting at only $469. Each mini comes with Apple’s one-year warranty, and shipping is free. The following... Read more
Apple to release updated AirPods Pro 2 with U...
Analyst Ming-Chi Kuo, in his latest post, suggests that Apple will soon release an updated version of AirPods Pro 2 with a new USB-C case, replacing the current case using an Apple Lightning... Read more
16″ M2 Pro MacBook Pros on sale for $150 off...
Apple retailer Expercom has 16″ M2 Pro MacBook Pros in stock today and on sale for $150 off MSRP, valid through March 28, 2023. In addition to their MacBook Pro sale prices, take $50 off AppleCare+... Read more
13-inch M2 MacBook Pros on sale for $100 off...
Expercom has 13″ MacBook Pros with Apple M2 processors in stock and on sale today for $100 off MSRP through March 28, 2023. Shipping is free: – 2022 13″ MacBook Pro M2 CPU/256GB SSD: $1199, save $100... Read more
Amazon is selling Apple’s 24″ M1 iMacs for $2...
Amazon has Apple’s 24″ M1 iMacs on sale for $200 off MSRP. Their prices are currently the lowest available for new iMacs among the Apple retailers we track: – 24″ M1 iMacs (8-Core CPU/7-Core GPU/... Read more
Apple’s 10th-generation 10.2″ iPads are on sa...
Amazon has Apple’s 10th-generation iPads on sale for $50 off MSRP starting at only $399. Their discount applies to all models and all colors. With the discount, Amazon’s prices are the lowest... Read more
Apple 13-inch MacBook Pros are on sale for $1...
Amazon has 13″ MacBook Pros with Apple M2 processors in stock and on sale today for $150 off MSRP. Their prices are the lowest currently available these MacBook Pros. Be sure to purchase from Amazon... Read more
Apple Pro Display XDR with Nano-Texture Glass...
Apple Authorized Retailer Adorama has the Pro Display XDR with Nano-Texture Glass on sale for $500 off MSRP today. Shipping is free: – Apple 27″ Pro Display XDR Nano-Texture Glass: $5499 $500 off... Read more
10-Core M1 Max Apple Mac Studio on sale for $...
Adorama has the base 10-Core M1 Max Mac Studio in stock and on sale today for $1799 including free shipping. Their price is $200 off Apple’s MSRP, and it’s the lowest price available for a new Mac... Read more

Jobs Board

Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Beauty Consultant - *Apple* Blossom Mall -...
Beauty Consultant - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Sales Floor Associate - *Apple* Blossom Mal...
Sales Floor Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.