VirtualMV/JavaScript/Starting/Functions

From WikiEducator
Jump to: navigation, search




Introduction

Overview

VmvIcon Objectives.png

By the end of this page you will be able to:

Functions

To create a function you define its name, any values ("arguments"), and some statements:

function fnFunction(argument1,argument2,etc) {
    some statements
} 
// no arguments, still requires parenthesis
function fnFunction() {
   some statements
} 
// functions can return a result
   function fnResult(a,b) {
   c=a+b;   
   return c;
}

Calling a function

fnFunction(argument1,argument2,etc)


Example 1: (js1_11)

<html>
<head>
<script type="text/javascript">
  function fnHello() {
    alert("HELLO");
  }
</script>
</head>
<body>
  <form>
    <input type="button" onclick="fnHello()" value="Call function" />
  </form>
  <p>By pressing the button, a function will be called. The function will alert a message.</p>
</body>
</html>
JavaScript: Button

Example :Click here to run js1_11.

Example 2: (js1_13)

<html>
<head>
<script type="text/javascript">
function fnAlert(txtMessage) {
    alert(txtMessage);
}
</script>
</head>
<body>
  <form>
    <input type="button" onclick="fnAlert('Good Morning!')" value="In the Morning">
    <input type="button" onclick="fnAlert('Good Evening!')" value="In the Evening">
  </form>
</body>
</html>
JavaScript: Function

Example :Click here to run js1_13.

Example 3: (js1_14)

<html>
<head>
<script type="text/javascript">
  function fnTotal(intA,intB) {
    return intA + intB;
  }
</script>
</head>
<body>
  <script type="text/javascript">
    document.write(fnTotal(2,3));
  </script>
  <p>The script in the body section calls a function with two arguments, 2 and 3.</p>
  <p>The function returns the sum of these two arguments.</p>
</body>
</html>

Example :Click here to run js1_14.


VmvIcon References.png References

virtualMV  |  Superquick wiki guide  |  Please give me some feedback

VirtualMV/JavaScript/Starting/Functions. (2017). In WikiEducator/VirtualMV wiki. Retrieved October 23, 2017, from http://wikieducator.org/VirtualMV/JavaScript/Starting/Functions    (zotero)