Saturday, April 30, 2011

JavaScript Functions - IX


In JavaScript, you will use functions a lot. A function (also known as a method) is a self-contained piece of code that performs a particular "function". You can recognise a function by its format - it's a piece of descriptive text, followed by open and close brackets.
Sometimes there will be text in between the brackets. This text is known as an argument. An argument is passed to the function to provide it with further info that it needs to process. This info could be different depending on the context in which the function is being called.

Arguments can be extremely handy, such as allowing your users to provide information (say via a form) that is passed to a function to process. For example, your users could enter their name into a form, and the function would take that name, do some processing, then present them with a personalised message that includes their name.
A function doesn't actually do anything until it is called. Once it is called, it takes any arguments, then performs it's function (whatever that may be).

Writing a function in JavaScript

It's not that hard to write a function in JavaScript. Here's an example of a JavaScript function.
Write the function:

<script type="text/javascript">
<!--
function displayMessage(firstName) {
    alert("Hello " + firstName + ", hope you like JavaScript functions!")
}
//-->
</script>
Call the function:

<form>
First name:
<input type="input" name="yourName" />
<input
  type="button"
  onclick="displayMessage(form.yourName.value)"
  value="Display Message" />
</form>
Exlanation of code
Writing the function:
  1. We started by using the function keyword. This tells the browser that a function is about to be defined
  2. Then we gave the function a name, so we made up our own name called "displayMessage". We specified the name of an argument ("firstName") that will be passed in to this function.
  3. After the function name came a curly bracket {. This opens the function. There is also a closing bracket later, to close the function.
  4. In between the curly brackets we write all our code for the function. In this case, we use JavaScript's built in alert()function to pop up a message for the user.
Calling the function:
  1. We created an HTML form with an input field and submit button
  2. We assigned a name ("yourName") to the input field
  3. We added the onclick event handler to the button. This event handler is called when the user clicks on the button (more about event handlers later). This is where we call our JavaScript function from. We pass it the value from the form's input field. We can reference this value by using "form.yourName.value".

No comments:

Post a Comment