JavaScript Functions and Methods

 

JavaScript Functions and Methods

This is part seven of the JavaScript tutorial. If you missed the previous lessons, make sure you complete them prior to viewing this JavaScript Functions and Methods tutorial.

Functions and methods are pretty much the same thing. However, you write functions that include event handlers, variables, and statements. In previous examples we saw a simple method, document.write. Document is the object, and write is the method. Functions are a little more detailed.

 

Look at the following piece of code:

<a href="#" onClick="alert(‘Three plus two is ‘ + addNumbers(3,2)); return false;">Add 3 + 2</a>

This piece of code would cause a small alert box to pop up on the screen that says Three plus two is 5. Note the # sign in the href tag. This is basically used as a place holder, because we want to use a link, but we don’t want that link to go anywhere. Also note that we have return false there, which tells the browser not to perform its default action when the link is clicked, which would normally be to take you to another page. All of this together is a function.

You can also use a function like this:

function popup()
{ alert(‘This is a popup’); }

In this example, you have actually specified that a function is being called, and the function is to popup an alert box that says This is a popup.

JavaScript functions are not loaded until they are called or until the user performs a certain action. Functions are placed in the HTML code in the <head></head> section. They can also be linked to in the head section if they are on a separate document.

Here is another example:

<html>
<head>
<script type="text/javascript">
function displaymessage()
{ alert("Welcome!") }
</script>
</head>
<body>
<form>
<input type="button" value="Click Here!" onclick="displaymessage()" >
</form>
</body>
</html>

 

Here we have placed a function in the <head></head> section of a webpage, and a button in the body of the web page that says Click Here. When this button is clicked by the user, an alert box will popup that says Welcome. Notice that after we write function, we use the displaymessage ( ). We state that we want to perform a function, and then define what that function is.

You will learn to use many different types of functions and methods as you go along. You don’t have to memorize all of them.

 
This concludes the JavaScript Functions and Methods lesson. In the next lesson, we will focus on JavaScript Errors.