JavaScript

Chapter 9 Functions and Parameters

Declaring a function

Functions are usually declared (defined) in the header element of the html document.

function someName()
{
JavaScript instructions go here
}

Calling a function

someName()

Functions with parameters

function printGreeting(personName)
{ alert("Hello, " + personName)
}

printGreeting("Fred")

This would produce the alert message:

Hello Fred

We can pass parameters that are numbers, strings or booleans.

Common functions are provided by the system, such as
document.write that displays the value of the input parameter.

If statement

if (booleanPredicate)
{ executeThisIfTrue }
else
{ executeThisIfFalse }


Sample JavaScripts:

IN THE BODY:

<html>
<body>

<script type="text/javascript">
document.write("<h1>Hello World!</h1>")
</script>

</body>
</html>

IN THE HEAD:

<html>
<head>
<script type="text/javascript">
function message()
{
alert("This alert box was called with the onload event")
}
</script>
</head>

<body onload="message()">

</body>
</html>

IF STATEMENT:

<html>
<body>

<script type="text/javascript">
var d = new Date()
var time = d.getHours()

if (time < 10)
{
document.write("<b>Good morning</b>")
}
else
{
document.write("<b>Good day</b>")
}
</script>

<p>
This example demonstrates the If...Else statement.
</p>

<p>
If the time on your browser is less than 10,
you will get a "Good morning" greeting.
Otherwise you will get a "Good day" greeting.
</p>

</body>
</html>

ALERT:

<html>
<head>
<script type="text/javascript">
function disp_alert()
{
alert("I am an alert box!!")
}
</script>
</head>
<body>

<input type="button" onclick="disp_alert()" value="Display alert box" />

</body>
</html>

PROMPT:

<html>
<head>
<script type="text/javascript">
function disp_prompt()
{
var name=prompt("Please enter your name","Harry Potter")
if (name!=null && name!="")
{
document.write("Hello " + name + "! How are you today?")
}
}
</script>
</head>
<body>

<input type="button" onclick="disp_prompt()" value="Display a prompt box" />

</body>
</html>

FUNCTIONS:

<html>
<head>

<script type="text/javascript">
function myfunction()
{
alert("HELLO")
}
</script>

</head>
<body>

<form>
<input type="button"
onclick="myfunction()"
value="Call function">
</form>

<p>By pressing the button, a function will be called. The function will alert a message.</p>

</body>
</html>

SELECTIVE ALERTS

<html>
<head>
<script type="text/javascript">
function myfunction(txt)
{
alert(txt)
}
</script>
</head>

 

<body>
<form>
<input type="button"
onclick="myfunction('Good Morning!')"
value="In the Morning">

<input type="button"
onclick="myfunction('Good Evening!')"
value="In the Evening">
</form>

<p>
When you click on one of the buttons, a function will be called. The function will alert
the argument that is passed to it.
</p>

</body>
</html>