JavaScript functions

You have just used a built-in JavaScript function called alert.  Someone elese wrote some code which you have been able to use by calling it by name (alert). 

You can create your own functions.  You put JavaScript code into a container and give it a name.  Then you can call the code by name from the HTML when you need it to run.

Save jsevent.html as jsfunction.html.  Add this script element just under the style element:

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

It will then be read by the browser before the page body is shown.  Nothing will happen because the browser knows that a function is a container for code to be run later.  Try it.

You should recognise the first line in the code above as it is HTML telling the browser that there is some script inside.  The second line tells the browser that this is the start of a function named fred.  The curly brackets (braces) enclose the JavaScript code which you want to run.  You should also recognise it as it is the only JavaScript you have learned so far!

Now that you have the function you need to set up the trigger which will cause the browser to run the code inside the function.  In your paragraph change the onmouseup attribute's value from alert('Hello again'); to fred(); which is the name of the function followed by the brackets which are the easy way to identify a function.

Before you try it you should try to understand the code to see what is now going to happen:

Try it.


One of the hardest thing when learning anything new is learning which words to use.  You should have picked up two new ones so far and here qare those two and one more:

You need those three things for any proper event-driven program to work (not just JavaScript).