Learning Javascript
Javascript is an extention of HTML. It can be writen into your pages, and run from them, in many ways.
<SCRIPT>
The simplest method to getting you codes to run is to place them in the <script>...</script> tags in the body of the document.
<script>
alert("Hello World")
<script>
When the page is opened the script will be executed as soon as the browser reads it. This is great for small scripts, but when the script refers to an object further down in the page, it will start to cause problems and crash the script. This is because that part of the page would not of loaded and the script does not know what to do. These scripts are best placed in the head tags so that they can be pre-loaded and executed when required.
Attached Code
Javascript code can be directly attached to the event handler of of an HTML object, and will be executed when the event occurs. More about event handlers later on.
<input type="button" value="Click" onClick="alert('Hi, Happy Learning')">
In this case, the event is a click from a button, and will display an alert message box.
Functions
A function is a piece of javascript code which on its self does nothing. It will be executed when it is called upon by a line from javascript in a <script> block or from an attached code in an object, somewhere in the <body> part of the document. The function script is written into the head part of the document.
<script>
function greetz()
{
alert("How Do You
Do?")
}
</script>
So when the browser sees the command to carry out grettz() it will display the message box How Do You Do? This can be placed in <script> tags.
<script>
greetz()
</script>
The (brackets) at the end of the function are essential and can be used to transfer information between the function and rest of the code. Remember that javascript is case sensitive.
Heres the basic layaout as to what we talked about above. Each coloured cell assiociates with another cell of that colour.
| <html> <head> |
||
| <script> function greetz() { alert("How Do You Do?") } <script> |
The Funtion is
definied as greetz. Any data passed onto an alert must be enclosed in (brackets). The Functions code must be enclosed in {curly brackets} |
|
| <title>Title
of Page</title> </head> <body> |
||
| <script> alert("Hi, Happy Learning") </script> |
Script that is embedded into the <body> area. | |
| <form> <input type="button" value="Click" onClick="alert('Have a Good Day!')"> </form> |
This code is attached as a button event. | |
| <script> greetz() </script> |
This call executes the function greetz(). | |
| </body> </html> |
You can have as many <script> blocks on a page as you want. |