|
|
JavaScript Functions - Creating and Using - 1Functions pack JavaScript statements in a block that can be used over and over again. Any programming language worth its salt allows coders to define and call functions. What are functions? - An example
<SCRIPT LANGUAGE="JavaScript" TYPE="TEXT/JAVASCRIPT">
<!--
function alert_box()
{
alert("I am displayed by a function");
document.bgColor="#EEEEEE";
}
//-->
</SCRIPT>
A function consists of the function keyword, the name of the function followed by a pair of parenthesis and lastly, the JavaScript statement/s enclosed by curly braces. You can give any name to the function as long as it is not a JavaScript reserved keyword. (The list of reserved keywords can be found here.) Some valid function names Some invalid function names Remember, function names are case sensitive, thus, alert_box is not the same as Alert_box. The function block can contain several JavaScript statements enclosed between the curly braces. The function in itself does not do anything till we call it. Calling functions <SCRIPT LANGUAGE="JavaScript" TYPE="TEXT/JAVASCRIPT"> <!-- alert_box(); //--> </SCRIPT> It's good programming practice to place all functions in the HEAD section of the HTML document between the <SCRIPT> - </SCRIPT> tags. Function calls, on the other hand, can occur in any part of the document (where ever they are needed!), even inside event handler code. Using a function call inside event handler code <A HREF="javascript:void(0)" onclick="alert_box()"> Function called thru an event handler</A> Here is how it works: Function called thru an event handlerYou'll notice that a function call looks very similar to calling a method. Now, wasn't that simple? Opening a new window through a function
<SCRIPT LANGUAGE="JavaScript" TYPE="TEXT/JAVASCRIPT">
<!--
function open_win()
{
window.open('welcome.html','welcome','width=300,height=200,
menubar=yes,status=yes,location=yes,
toolbar=yes,scrollbars=yes');
}
//-->
</SCRIPT>
Note: the entire JavaScript code should be placed on a single line. For clarity, I have put the code on multiple lines. <A HREF="javascript:void(0)" onclick="open_win()"> Get a welcome message</A>Get a welcome message Really appreciating functions
Page contents: Javascript functions - using javascript functions - create javascript function
Page URL: http://www.webdevelopersnotes.com/tutorials/javascript/ creating_javascript_functions.php3
|
|