Wednesday, July 23, 2008

JavaScript onClick Event


This is another "Hello World" example using JavaScript. The example below is a html script that is embedded with a javascript that will display a message in a messagebox whenever the button is clicked.

Your javascript must be placed inside the <head> </head> section of your html code. The javascript code must also be enclosed with the tag <script> </script>. Inside the <script> tag, you need to set the language property to "javascript".

The script is simple, we declare a new function called greet() and when this function is called, it will call a javascript built-in function called alert(). The alert function will pop-up a messagebox displaying the string "Hello! How are you today?".

Now that we have our javascript, we need to call the greet() function whenever a certain event is triggered. In this example, we added a button in our html code and set the onClick event of this button to call the function greet().

You try clicking the "Hello World" button below to see the output of this script.


The Script

<html>
<head>
<title>Yet another Hello World</title>
<script language="javascript">
function greet()
{
alert("Hello! How are you today?");
}
</script>
</head>
<body>
<form name="Form1">
<input type="button"
name="btnGreeter"
value="Hello World"
onclick="greet()" />
</form>
</body>
</html>


The Output





No comments: