JavaScript Basics :
FUNCTIONS








Instead of just adding your javascript to the page and having the browser perform the tasks as soon as the script is read, you might want your javascript to be performed only upon the detection of a certain event.

For example, if you made a javascript code that changed the background color of the page when the user clicked a button, then you would need to tell the browser, that the script should not be performed right away when loaded.

To keep the browser from performing a script as soon as it is loaded you need to write the script as a function.

Javascript written into functions will not be performed until you specifically ask for it. This way you gain complete control of the timing.

Look at this example of script lines written as a function:

<html>
<head>
<script>
function myfunction()
{
alert("Welcome to my world!!");
}

</script>
</head>

<body>
<form name="myform">
<input type="button" value="Hit me" onclick="myfunction()">
</form>
</body>
</html>


Click the button to see what the script in the example does:







If the line: alert("Welcome to my world!!"); had not been written within a function, it would simply be performed as soon as the line was loaded.

But since we wrote it as a function, it was not performed until you hit the button.




The call of the function is in this line:

<input type="button" value="Click Here" onclick="myfunction()">


As you can see, we placed the button in a form and added the event onClick="myfunction()" to the properties of the button.

The next page gives a detailed description of the different events you could use to trigger functions.




The general syntax for a function is:

function functionname(variable1, variable2,..., variableX)
{

// Here goes the javascript lines for the function
}





The { and the } marks the start and end of the function.





A typical bug when entering javascript functions is to forget about the importance of capitals in javascript. The word function must be spelled exactly as function. Function or FUNCTION would cause an error.

Furthermore, use of capitals matters in the name of the function as well. If you had a function called myfunction() it would cause an error if you referred to it as Myfunction(), MYFUNCTION() or MyFunction().

 << PREVIOUS
READ MORE >>  
















DEVELOPER TIP!





     "Better Than Books - As Easy As It Gets!"