What’s a Function?

A function is a piece of code that sits dormant until it is referenced or called upon to do its “function”. In addition to controllable execution, functions are also a great time saver for doing repetitive tasks.
Instead of having to type out the code every time you want something done, you can simply call the function multiple times to get the same effect. This benefit is also known as “code reusability”.

Example Function in JavaScript

A function that does not execute when a page loads should be placed inside the head of your HTML document. Creating a function is really quite easy. All you have to do is tell the browser you’re making a function, give the function a name, and then write the JavaScript like normal. Below is the example alert function from the previous lesson.

HTML & JavaScript Code:

<html>
<head>
<script type="text/javascript">
<!--
function popup() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="popup()" value="popup">
</body>
</html>

We first told the browser we were going to be using a function by typing “function”. Next, we gave our function a name, so that we could use it later. Since we are making a pop up alert, we called our function “popup”.
The curly braces “{,}” define the boundaries of our function code. All popup function code must be contained within the curly braces.
Something that might be slightly confusing is that within our “popup” function, we use another function called “alert,” which brings up a popup box with the text that we supply it. It is perfectly OK to use functions within functions, like we have done here. Furthermore, this is one of the great things about using functions!
What we didn’t talk about was how we got this function to execute when the button is clicked. The click is called an event, and we will be talking about how to make functions execute from various types of events in the next

0 comments:

Post a Comment

 
Top
Blogger Template