Introductory lines
The pyramids of Egypt are the most eloquent hold-outs on the age-old bromide that simple tools and techniques do not essentially have to produce bland, unglamorous results. They can also trigger off monumental creations that speak to everyone who visits them. Java Script, the latest offering from the IT industry's bigwig-duo Sun Microsystems and Netscape, is very much in the same domains. Quite simple in its basic mechanisms, yet holding the promise of sprucing up (revolutionizing) the vast skeins of the World Wide Web. In this issue, you will learn some of the rudimentary stuff about Java Script and what underlies the so-called dynamic future.
There is something rather spooky about the epithet "Java". You (christen ) name a chunk of islands after it and they become international tourism hotcakes. Pour yourself a cuppa coffee and call it Java to send the cafe's trial balance snowballing. Brew up a set of accoutrements for a computer programming language, give it the magic title and it is touted to plateau the brand equity of a biggie like Microsoft. Trouble is, it does. Pick out some disregarded product "Live script" from some dark and deserted cubbyhole, sprinkle the may-dew of this divine beverage (call it "Java script", that is) and whoa! it becomes the best thing that ever happened to the human race after the "man on the moon". Almost all, if not all, the ions in the IT industry swoop down with dripping tongues on the treasure trove and label it the sure-fire prototype of a dynamic future. Infact, it sends big rats (in the race, ofcourse) like Microsoft staggering back to garret!
The point is, to put it in a politically correct manner, the association of logic and the computer industry is a misnomer idea in the first place. And therein lies the rub of the World Wide Web. It is totally unpredictable, absolutely anarchaic and outright post-judiced, strung together with shocks of illogicality.
Yet, lets face it. As it stands today, all the furnishings of the glamorous web are based on the underpinnings of HTML (that's HyperText MarkUp Language, for the out-of-touch). There's more to establishing presence on the web than mastering the ins and outs of Hyper Text. If your most fiendish nightmare is falling out of the rat race, if there is one, then you'd better re-think your Web-oriented efforts. The rather drab HTML is already considered primitive. Its the likes of Java script and Netscape plug-ins that are calling the shots.
Java script has its rhizome in HTML. Infact, quite like the Web, the two are so inextricably intertwined that to really comprehend the whys and wherefores of Javascript, we will have to take a brief detour back to its ancestor HTML.
Including tags along with text is what demarcates HTML from any ordinary ASCII file. In HTML, the tags are enclosed within angle brackets. For instance, a document heading is indicated with <H1>. Since most of these tags travel in pairs, a <H1> marks the beginning of a heading and a corresponding </H1> marks its end. Likewise, a word within the tags <b> and </b> will instruct your browser that the word has to displayed in Bold. That's the reason why it is called scripting language, because anything between the less than sign and a greater than sign is understood by the browser.
One finds, after a short spell with HTML, that its beauty lies in the fact that it is a stream of plain, old characters. Which makes any half-witted text editor a potential HTML generator. There is no dearth of programs like WordPerfect where you create your page, pictures and all, and it will create a corresponding HTML file automatically. Therefore, it is rather silly to call it a programming language as it is popularly misidentified, unless you think that adding a couple of dumb stubs or tags is equivalent to programming. Strictly speaking, it does not allow any intelligent functionalities, say, the for the if statements. That is where Java script makes its glorious entry. It has functions, loops, variables and not to forget objects (which you can spend your life researching and still never get to know what they really are).
Just a widget of wisdom before we begin to grapple with the innards of Java script. Using a scripting language is pointless if you are not working with the Internet and specifically, the World Wide Web. They are not generalised languages like C/C++ or talking of the more in-thing, Java. One would be a minimalist bumpkin if he/she intended using something like PowerBuilder or Visual Basic to program a spaceship directed towards Mars, while C could prove helpful. (Infact, a language like C is so generically applicable, it could very well be used to grow water melons). PowerBuilder servers well as a front end to databases only and it is sensible to restrict it to that level. In the same vein, Java Script has been designed to work with HTML. Second and very important, Netscape is the only known browser to support Javascript. Now.
With that nugget up our sleeve, lets whip the horse. Consider the following code...
1.html
<SCRIPT>
document.writeln("Hello");
</SCRIPT>
This code has to written and saved as an HTML file. To try the code out, load the HTML file in your browser. The script tag tells my browser that everything inside it is Javascript code. That is, whatever you write within the two tags is taken to be part of Java Script. As a part of the code, we have document.writeln. A document is an object that refers to the entire document or form that you are currently in.
As regards the million-dollar query "What's an object", well that remains a fairly brilliant question, only that there is no immediately convincing answer. One can live out fairly long life without being able to define an object for the simple reason that everything around us is an object -- from the spider's cobweb above you to this article or a magazine you are reading. Infact, one can live out a fairly cheerful life without ever needing to define an object.
Since the analogy here is a magazine, let us take that. A magazine has pages, the pages have words, the words have letters of the alphabet etc. If magazine were an object, the pages would be the members. Similarly, our object in question document has members -- in the form of variables and functions. writeln is a function, as is apparent, looking at the round brackets that follow it. The period '.' seperates the function from its superordinate object (i.e, it seperates writeln from document).
We pass Hello as a parameter to the writeln function. The work of writeln is to instruct the browser to display on the screen whatever is passed to it (writeln) as a parameter. Therefore, when you now load the above HTML file, you will see the word Hello in your Netscape browser. At this point, try snipping out those script tags.
2.html
document.writeln("Hello");
Since the tags are absconding, the browser will refuse to recognize the line as a Javascript and display the whole thing -- document.writeln("Hello");
Note that unlike C or C++, Java script is not ruthlessly unforgiving if you skip the semicolon at the end of the line of code. As a slight deviation, try this out...
3.html
<SCRIPT>
document.writeln("<H1> Hello </H1>");
</SCRIPT>
As discussed earlier, the H1 tag represents that a heading. Since we specify this inside the writeln, the browser will sniff out the same Hello as a heading -- bigger, bolder, better.
4.html
<SCRIPT>
document.writeln(" <IMG SRC = \"joe.surf.yellow.small.gif\"> ");
</SCRIPT>
The <IMG> tag forewarns the browser that an image is on its way. The browser makes arrangements accordingly to display the image. Here we use a .gif file that contains a picture. (For the people in the dark, .gif stands for Graphical Interface Format). Obediently, the browser will display the image provided the .gif file is present in the current directory. Alternatively, the entire path of the file can be specified. Notice the backslash '\' before the quotes that contain the name of the file. If we do not specify a slash there, the browser will understand it to be the end of the double quote pair that starts from the one before IMG tag. Therefore, to avoid the confusion with four double inverted commas, we put the slash. A backslash tells the browser to ignore the character immediately following it.
5.html
<SCRIPT> document.fgcolor = "#ff0000" </SCRIPT> <FORM> good boy </FORM>
That fgcolor stands for "foregroung colour". Our object document also has a variable called fgcolor. We initialize this variable to a hexadecimal number. Let us not bother ourselves with hexadecimal rhetoric lest we should need a dozen aspirins. We learnt in school about the three primary colours -- RGB, i.e, Red, Green and Blue. It ought to suffice to sat at this juncture that the ff in the hex number above stands for full red. The remaining pairs of zeroes representing the green and the blue element in the overall foreground colour (they are both zero, thus making the foreground entirely red). Note that the value/density of the three basic elements in a given colour can range from 0 to 255.
The tag <FORM> comes from the good, ol' HTML. Whatever is between <FORM> and </FORM> means it will be displayed immediately on the screen. Since our foreground colour is red, good boy will be displayed in red. If we set the foreground colour, it will not take a Sherlock Holmes to tell that we can do the same for background colour as well. Consider the next one ...
6.html
<SCRIPT> document.bgcolor = "#ff0000" </SCRIPT> <FORM> good boy </FORM>
Since the the background color is made red, the screen will be in red. At this point of time whether you have a <form> and a </form> does not make a difference. Next...
7.html
<SCRIPT> document.fgcolor = "#ff0000" </SCRIPT> <FORM> <INPUT TYPE = "button" VALUE = "Press Me"> </FORM>
For the ones who came in late, INPUT is a word that HTML knows. TYPE is another word HTML is well acquainted with and it can be used only after the word INPUT (as that's a part of unarguable syntax, we try to be obedient). Now when we say button with the value being "Press Me", we will see a small command button on the screen with "Press Me" as its label. That's because we said the TYPE was button and the VALUE was "Press Me". But as of now, clicking on the button does not wake up the button. To trap a click of a button, Javascript provides an additional facility called "onClick". Try the next program...
8.html
<FORM>
<INPUT TYPE = "button" VALUE = "Press Me" onClick = "alert('good')">
</FORM>
Mark the case and stick by it for Java script is not as lenient with case-typos as with semicolons. An onClick inside an INPUT statement ensures that whatever follows it will get executed. OnClick is added to input, it is a part of JavaScript. Here we give an alert() after the onClick with the parameter good. An alert() is a global function that can be called from any nook of the program. In our case, it will bring us a message box with good displayed in it. Note that the contents of onClick are stuffed inside double quotes while good is within single quotes. A slightly differently different from the alert() is the confirm() which boasts a couple of additional buttons -- OK and CANCEL. The following program should make that adequately clear...
9.html
<FORM>
<INPUT TYPE = "button" VALUE = "Press Me" onClick = "confirm('good')">
</FORM>
That demonstrates one of the reasons why people love using Java script -- it has a large number of built in functions like these. In the next example you get the same answer , the only difference being that we do not use confirm directly.
10.html
<SCRIPT>
function aaa()
{
confirm("good")
}
</SCRIPT>
<FORM>
<INPUT TYPE = "button" VALUE = "Press Me" onClick = "aaa()">
</FORM>
Since smooshing multiple options on the same line in INPUT can be a trifle cumbersome, we define our own function called aaa(). Now when the user clicks with the mouse, the aaa() gets called to display the confirm box. This also serves a dual purpose. We can now do an array of complex things inside our function and call it with the click of a mouse! The next example says that each time you click on the button, the background color will change.
11.html
<SCRIPT>
function aaa()
{
document.bgcolor = "#ff0000"
}
</SCRIPT>
<FORM>
<INPUT TYPE = "button" VALUE = "Press Me" onClick = "aaa()">
</FORM>
The true strength of JavaScript comes on with the objects that it gives you. It gives us an interesting object called history. Consider the following code...
12.html
<SCRIPT>
function aaa()
{
history.go(-1)
}
</SCRIPT>
<FORM>
<INPUT TYPE = "button" VALUE = "Press Me" onClick = "aaa()">
</FORM>
As is adequately explicit, the above code makes use of a function called go() that comes with the object history. We pass a parameter of -1 which means that it will take us to the previous page. Let us make it a little clearer. When you are browsing on the web, you flip through screenfuls of pages. If you want to move to the previous page at any given point of time, you just click on the button that says "Back". (And we are talking Netscape here). The go(-1) works precisely like that. Your HTML program can now cruise through the various ages that a user has been surfing through. You could have a couple of buttons, one with a label of a left arrow (<-) and the other with a right arrow (->). When the user clicks on the left arrow, you could take him one page back (with go(-1) ) and (with go(+1) ) forth in the history. consider the following...
13.html
<SCRIPT>
function aaa()
{
alert(history.current)
}
</SCRIPT>
<FORM>
<INPUT TYPE = "button" VALUE = "Press Me" onClick = "aaa()">
</FORM>
Like any other object, history has its set of functions and variables. current is a variable that tells you where the user is in history, i.e., on which page is he since the time he started surfing this time. So thats what we are displaying in the alert message box.
Given above are only a few examples of Java Script along with the explanations to them. Many more script programs can be tried out from More Java Script Examples
Email us your comments, feedback, suggestions.
Back to VIJAY MUKHI'S TECHNOLOGY CORNUCOPIA
This tutorial is a joint effort of
Vijay Mukhi
Sonal Kotecha
Shashank Tripathi