Monday, February 21, 2011

Hello World in Javascript

I am a python fan but I have to come to grips with javascript since I am also programming an online solver site. Javascript can be processed by any browser unless the javascript engine has been turned off by the user,perhaps due to security concerns.

Here we show a simple html file with embedded javascript code to write a message "Hello World!".This example is only useful in the sense that the aspiring javascript coder will be familiar with the standard practices of writing Java script. We will later introduce more complex and useful examples.


Now open your editor, copy manually or just cut and paste the following contents.

<html>
<head>
<title> Hello World Example</title>

<script language="javascript"> 
function showMessage(message)
{
   document.getElementById('location').innerHTML= message;
}
</script>
</head>

<body onload="showMessage('Hello World!')">
<h1>A first Javascript</h1>

A message to one and all:

<span id="location"></span>

</body>
</html>

Lets get this to work. Fire up your browser and enter the url, (uniform resource locator), of the file
In my case, it was "file:///home/toto/Blogs/my-other-life-as-programmer/javascript/hello-world.html"

The output window should look like this:

Note that you do not really need Javascript just to print a message which can be read by all browsers!
A pure html will do, but in the above code, (based on Holzer's XML bible), the use of function is illustrated. So it is a little complicated.

The function is declared inside the html header <head> block by the xml delimiters <script language="javascript">.... function here!.... </script>.When your browser encounters this script block, it does not right away execute it but parses the contents, translates it into a form for faster execution and saves it for recall.

Notice that the body of the function will find a named div block called "location" and it will insert
any message specifid by function's input argument. The function is triggered when the browser loads the html page (the body block). When it encounters the inline <span id="location" > block, the function replaces this block by message "Hello World".

The main behavioral difference of a span and div block is that a line break is always inserted by the div block. whereas the span is inline.

For more information, consult the introductory javascript chapter in


Steven Holzner: "AJAX Bible", John Wiley, 2007.

The book book has a fast pace introduction to Javascript, for a more relaxing pace, perhaps the following is more suitable:

Tom Negrino, Dori Smith: "JavaScript for the World Wide Web", Peachpit Press,2004.

I have both books, bought at Booksale. I consider them bargains at this time, costing me 350 and 200 pesos respectively

.






javascript:void(0)

No comments:

Post a Comment