Current course:



A function contains code that can be executed by an event or by a call to the function. Functions are often used when you need to do something more than once, with the same or similar results.

The Code:

      <script type="text/javascript">
            function myAlert(msg) {

      <a href="#" onmouseup="myAlert('test');">Alert "test"</a><br />
      <a href="#" onmouseup="myAlert('pizza');">Alert "pizza"</a>


Alert "test"
Alert "pizza"


First we create a javascript function called "myAlert" (you can call it whatever you'd like).
A function always starts with "function", then a space, then the name of the function.

After the function name, you must always have an open and closed parenthasis.
Although you don't NEED anything in the parenthasis, in this case, we'd like to pass our function a variable. To do so, we must include the name of our variable between the open and closed parenthasis. Our variable is called "msg".

After the parenthasis, we "open" the function with a "{" and close it with "}" (without the quotation marks).
Everything between the { and the } is the contents of the function and will be run when the function is called.

We then create two links, which call the "myAlert" function.
To call a function, you must use the function name, and an open and closed parenthasis.

Within the parenthasis, you must match the number of variables the function "calls for". In this case, our function requires one variable (because we put one thing inside the parenthasis when we created our function.

So, to call our function, we use: myAlert("something")

When javascript reads this code, it will run the contents of our function, and replace msg with "something".

So, for our example, the first link will alert "test", and the second will alert "pizza".