AlfieWebDevTips Homefor new and experienced developers
[Home Home] [Web Development Web Development ] [Code Generators Code Generators ] [Resources Resources ] [Contact Us Contact ] |WebDevTips Privacy Privacy |
Print This Page

You are here : Home - Web Development - Javascript - Getting Started - Functions

Functions



Javascript functions are reusable blocks of code that can make life so much easier.

If you have done any programming then you can think of functions as similar to subroutines. This section will show you typical syntax and how to call the function. Try example 3

Example 3 code

<html> 
<head> 
    <title>Example 3</title> 
<script language="JavaScript" type="text/javascript"> 
<!-- 
function example1(){ 
alert("This is Example 1"); 

 
function example2(){ 
alert("This is Example 2"); 

// -->
 
</script> 
<noscript>Example javascript functions</noscript> 
</head> 
<body> 
<a href="#" onClick="example1();return false;">Test Function 1</a><br> 
<a href="#" onClick="example2();return false;">Test Function 2</a><br> 
</body> 
</html> 

The function syntax is

function NAME(){ 
Your Code 
}

Give your functions an appropriate name, it makes maintenance easier. Notice that () appear after the function name, make sure that there is no space before the () - example myfunction()

The code for the function must be placed between the {} for the function to work properly.

In the above example we are calling the function from an onclick event. The action we want to apply to the onclick event is example1(); - By clicking on the link text, the code within the example1 function is run.

We will expand on using functions after an introduction to variables.




16 Nov 2003




Google
 

[back to top of page]   

[labelled with icra -  - this link will open in a new window] [RSS Content]

[Copyright © WebDevTips]