Your first Javascript function

Placing the JavaScript as a value to an attribute in an HTML tag could end up with some very complicated code layout which would make it hard to understand even the HTML. Instead the JavaScript is put in the HEAD section much like embedded CSS.

First you need to create a place in the HEAD for the JavaScript and you do that simply by putting SCRIPT tags there.

Inside the SCRIPT tags you put a function:

<script type="text/javascript">
    function fred() {                
        alert('Hello for one last time');                
    }            
</script>
        

The function is first labelled as a function and then comes its name (fred here but it could be almost anything). Then curly brackets (braces) just like CSS. Inside the braces is the function. This function contsains code which is almost identical to what was inside the SCRIPT tags or the onmouseover attribute/event on previous pages.

Paste this whole thing into the HEAD of a Web page and load the page and nothing should happen.

Functions are containers for code which will be used later. To trigger a function you use an event trigger:

<p>Try hovering over the red words <span onmouseover="fred();" style="color:red;">just here</span> to see what happens.</p>
        

You should be able to see that the function is triggered (or called) by the fred() bit. For this simple example you could just put the actual alert code in the HTML but get into the habit of using functions as this will pay off later.

One last thing to note. All JavaScript lines of code should end with a ;. Often they will work anyway but the correct way is to use the semi-colon.

submit to reddit Delicious Tweet