Tuesday, April 14, 2009

JavaScript and Simple Interaction with the User




Alert Boxes (dialogs) are similar to AppleScript dialogs in that they communicate the state of something to the user. While AppleScript dialogs can be used in web pages as well as on the desktop, JavaScript dialogs are used almost exclusively for the internet.

In this, the first post on this topic, I will use the various types of JavaScript 'Boxes' to illustrate some of the basics of the JavaScript syntax.

Although you can call for an external JavaScript, they are most commonly placed within either the
<head>
tag or the <body>
tag of an HTML page:


<head>
<script type="text/javascript">
function userAlert()
{
alert("Welcome to my web page");
}
</script>
</head>





When you place a function, in this case an alert dialog, within the head tag, it 'preloads' the function when the page is displayed so that when it is needed there is no delay. You must begin with the statement '<script type="text/javascript">'
, which tells your computer to expect something with the JavaScript syntax.

Next, the name of the function (case sensitive, ie: userAlert() and useralert() are not the same and could be two totally different functions).

Then the statements, each line ending with ';' and an entire block of statements enclosed by '{}' Note that in a single statement block such as the one above the so-called 'curly brackets are optional'.

In the body section of the page:

<body>
<input type="button" onclick="userAlert()" value="Display alert" />
</body>


Click the button below to see the dialog



input type="button"
says to display a button on the page and value="Display alert"
says that the button will bear the name "Display alert".

Lastly,
onclick="userAlert()"
tells JavaScript that when the button is clicked, to execute what is in the preloaded function 'userAlert'.



If you have questions or would like to suggest a post on another JavaScript issue, contact me at: hyperscripter@gmail.com or http://twitter.com/hyperscripter