Back

Javascript

Functions and Events

Example 1

What if we want to show an alert when a word is clicked?

Create a new document. Put the following lines in the head of your document. Be careful to copy punctuation and capitalization exactly as they are shown!

<script type="text/javascript">
function showMsg() {
alert("Hello, world!");
}
</script>

Then put the code below in the body of your document. Save and preview. What happens when you click on "Click me to show a greeting!"?

<p onclick="showMsg()">Click me to show a greeting!<p>

Example 2

The keyword onclick is a type of event. An event occurs when the person viewing the page does something — for example, clicks something, moves the mouse, or loads the page. When an event occurs, we call a function to respond to the event. A function is like a little machine that produces a predictable result.

To explore this idea further, try adding a new paragraph and a new function to your web page. The paragraph should say: "Click me to see your lucky number for the day!" When clicked, it should call a new function that shows a lucky number.

Example 3

Here's another event that's often used: onload. The onload event occurs within the <body> tag, as shown below. Add it to your document. Save and preview. When does the onload event occur?

<body onload="showMsg()">

Example 4

Take a moment to remove the onload event from the body tag. It will interfere with our next experiment.

Here's another pair of events that are lots of fun to use: onmouseover and onmouseout. To see how they work, make the following changes to your document. Then save and preview.

Add the following paragraph to the body of your document.
<p id="target" onmouseover="changeColors( 'red' )" onmouseout="changeColors( 'blue' )">Mouse over me!</p>

Add the following two functions to the head of your document.
<script type="text/javascript">
function changeColors( newColor ) {
     var changeMe = document.getElementById("target");
     changeMe.style.color = newColor;
}
</script>

What does id="target" do? What does document.getElementById("target") do? How does the function changeColor() know what color to use -- red or blue?