An Introduction to Behaviors
To understand how behaviors in Dreamweaver work is to understand the fundamentals of JavaScript. Similar to CSS, JavaScript code is written within the <head> tag of your web page. Unlike CSS, which is written within a <style> declaration block, JavaScript is written within a <script> declaration block complete with the language attribute defining the language to be written in the script. A typical declaration block for a page might look something like this:
As you can see from the sample, the code declaration block acts as a container for the logic within the web page. Of course, this code sample is merely a shell of the functionality. To make the page a bit more interactive, we would add three components to this example: an object, an event, and a function that represents the action we want performed. The final product might resemble something like this:
&l230>
<head>
<title>Sample JavaScript</title>
<script language="JavaScript">
</script>
</head>
<body>
</body>
</html>
In this case, a Button form object is added as a way for the user to initiate the interaction between themselves and the page. Second, the onClick event is added as an attribute to the object. Although dozens of events exist for various types of objects, the onClick event exists as a way of alerting the browser that when the button is clicked, the showMessage() function should be called, and the code contained within the function should be executed. Finally, the function showMessage() is added in the code declaration block. This is where JavaScript gets complex because it represents the functionality we want performed when the user clicks the button. In our case, we want to show a pop-up message with the text Hello . To do this, we access the built-in alert() method of the window object and pass in the literal text "Hello" as a parameter to the alert() method. When all is said and done, the user clicks the button on the page to receive a message similar to Figure 10.1.
&l230>
<head>
<title>Sample JavaScript</title>
<script language="JavaScript">
function showMessage() {
window.alert("Hello");
}
</script>
</head>
<body>
<input type="button" value="Click Me" onClick="showMessage();" />
</body>
</html>
Figure 10.1. Clicking the button raises the onClick event which in turn calls the showMessage() function. After the function is called, the code is executed, and a message appears.
