Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Design > Voices That Matter

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Working with Behaviors

Ah, behaviors! This is where the glitz comes in, all those neat little prewritten JavaScripts that Dreamweaver allows you to add to your web pages at the click of a button. Believe it or not, basic behaviors are only slightly more complicated than objects to create—though, as always, the more you know about JavaScript, the better (and more spectacular) your results will be.

In this section, you'll learn what a well-formed behavior file looks like, how Dreamweaver processes behavior files, and how to build your own behaviors from scratch.

What Are Behaviors?

A behavior, like an object, is a snippet of code that gets inserted into a Dreamweaver document when the user chooses from the behaviors list. Instead of adding HTML code to the document (also like an object), however, a behavior adds JavaScript code.

Behaviors are constructed the same way objects are: Dreamweaver API procedures and functions enable you to return the exact string of code that you want inserted into your document.

For a variety of reasons, however, behaviors are inherently more complex than objects:

  • A behavior inserts two pieces of code—a function (in the document head) and a function call (in the body section, wherever the cursor is when the behavior is chosen).

  • Preferably, a behavior should be editable after it has been inserted, by double-clicking it in the Behavior panel. (To edit objects after they've been inserted, you use the Property Inspector. Although it is possible to create a custom Property Inspector, it's not a task for the faint of heart.)

  • Preferably, a behavior should specify which event handlers can be used in the function call; it should be inaccessible in the behaviors list (grayed out) if the current selection is inappropriate.

NOTE

Dreamweaver behaviors always insert JavaScript code into the document in the form of a generic function, defined in the head section, and a customized function call, defined in the body.

What Files, Where

Like objects, each behavior consists of an HTML file (the behavior file), which either contains JavaScript code or is linked to an external JS file. Behavior files are stored in the Configuration/Behaviors/Actions folder. Like the Objects folder, the Actions folder can contain folders inside itself; each folder corresponds to a submenu within the behaviors list. Again like the Objects folder, any new folder added to the Actions folder will result in a new submenu in the behaviors list (see Figure 22.15).

Structure of a Simple Behavior File

Like object files, behavior files have their own required structure, and Dreamweaver has a set procedure for dealing with them. Figure 22.16 shows the framework code of a basic behavior file, containing only the required elements.

The key elements of the file are listed here:

  • Page title. This becomes the name of the behavior as it appears in the behaviors list.

  • Defined function. This is the JavaScript function that the behavior will insert in the head section of the user's document. It will be inserted exactly as coded here. This function must have a unique name—no other defined function in the entire Actions folder can use this name.

Figure 22.15 The Actions folder, showing its subfolders, and the corresponding submenus in the Behavior panel's behavior list.

  • behaviorFunction() function. This JavaScript function, part of the Dreamweaver API, must return the name of the function defined previously (without the ending parentheses). This function is called automatically when the behavior is chosen and, therefore, needn't be called in the behavior file.

  • applyBehavior() function. This function, also part of the Dreamweaver API, must return the exact code of the function call as it will be inserted into the user's document. In a more complex behavior that requires arguments to be passed to the function, those arguments must be included in the return statement. This function is called automatically when the behavior is chosen and, therefore, needn't be called in the behavior file.

  • <body> tag elements. Any code in the body section of the file will appear in a dialog box when the behavior is chosen. All behaviors automatically call up dialog boxes. If the behavior requires user input, create a form (as with object files). If the behavior requires no user input (as in the example here), some content must be placed in the body, or an empty dialog box will appear.

Figure 22.16 The code framework required for a basic behavior file.

In the example shown in Figure 22.16, the function returned is a simple pop-up alert. Notice how the function and function call appear in the user's document, exactly as presented in the code.

Structure of a Fancier Behavior with a Dialog Box and Other Refinements

The behavior shown previously contains all the necessary elements and will work properly. However, it is unusually simple (requiring no user input and passing no arguments from the function call to the function), and it is missing several key enhancements (such as control over the event handler used and features that will allow the behavior to be edited in the future). Figure 22.17 shows the code for a more full-featured behavior, complete with all these (optional) features.

Figure 22.17 The code framework for a full-featured behavior file.

In addition to the elements listed, the key elements in this more full-featured behavior are as follows:

  • HTML form. As with object files, the form becomes the dialog box for collecting user input. In behavior files, the form is used to collect arguments for the function call to pass to the main function.

  • Link to script.js file. This link gives you access to several utility functions for handling strings; one of these functions, the extractArgs() function, is extremely useful in coding the otherwise complex inspectBehavior() function, listed later.

  • canAcceptBehavior() function. This function, part of the API, returns either true, false, or a list of one or more default event handlers. In more advanced files than the one shown here, this function can also determine what kind of object the user has selected in the document, and whether that object is acceptable for applying this behavior. If the function returns false, the behavior will appear grayed out in the behaviors list. This function is called automatically.

NOTE

Determining when a behavior should be grayed out in the behaviors list requires more in-depth knowledge of the Dreamweaver API and the Dreamweaver document object model (DOM) than is possible in this chapter. Read the Extending Dreamweaver manual and examine other behaviors to learn more about this.

  • inspectBehavior(functionCall) function. Also part of the API, this function must be used to collect information from a behavior that has already been applied and to repopulate the behavior's dialog box for editing. This function makes it possible for the user to open the Behavior panel, double-click an existing behavior, and be presented with a dialog box that contains the current settings for that behavior. The function is called automatically. Dreamweaver automatically passes the behavior's function call, as a string, to the function.

  • initializeUI() function. This function, which is not part of the API, does the same thing in behavior files as it does in object files: It places the cursor in a certain field of the dialog box and selects any contents for easier text entry. This function must be called using the onLoad event handler in the <body> tag.

In the example shown in Figure 22.17, the code returned by the defined function is a pop-up alert message, but with the content to be determined by the user. Notice that the defined function itself remains generic; the input collected by the form is used to add an argument to the function call.

Making Your Own Behaviors

In this section, you'll get some hands-on experience making your own behaviors. It should go without saying that you need to be able to write and understand the code for a particular JavaScript function and function call before you can turn that code into a behavior.

Exercise 22.7 Setting Up Shop

Start by getting your working space in order. As you did with objects previously, you'll create a custom behaviors folder for storing your exercise behaviors, and you'll learn a few of the quirks of reloading extensions when working with behaviors.

  1. Make sure that Dreamweaver is running. One of the goals of this exercise is to see how behavior extensions reload.

  2. Find and open the Configuration/Behaviors/Actions folder on your hard drive. Minimize or hide Dreamweaver, if necessary, so that you have access to your desktop.

  3. Create a custom behaviors folder. In the Actions folder, create a new folder. Call it Development. Leave the folder empty for now.

  4. In Dreamweaver, reload extensions. Ctrl/Opt-click the triangle at the top of the Objects panel, and choose Reload Extensions—this is the same procedure you followed when working with objects.

  5. In the Behavior panel, access the behaviors list and look for a new submenu. Click the + sign in the inspector to open the behaviors list. A new folder should result in a new submenu appearing in the list.

  6. Probably, however, you won't see any new Development submenu. Why not? Reloading extensions does not cause Dreamweaver to recognize new or renamed files or folders in the Actions folder; it recognizes only modifications within files. To get Dreamweaver to see the new submenu, you'll have to do it the old-fashioned way: Quit the program and launch again.

  7. Quit Dreamweaver and relaunch it. Then look again for the submenu. This time, your submenu should appear. Of course, it will be an empty submenu because the Development folder is empty. But your new behaviors will appear there. Every time you add a new behavior, you must quit and relaunch; when you modify an existing behavior, you can reload extensions without quitting.

Exercise 22.8 Making a Simple Behavior

A simple behavior is one that doesn't require arguments to be passed from the function call to the function and that, therefore, doesn't need a form to collect user input. The simple behavior that you'll create in this exercise is a script that automatically resizes the browser window to a certain size.

Create and edit the exercise files in your favorite text editor or in Dreamweaver's Code Inspector. Save the behavior file into the Development folder created in the previous exercise. Save the test files in your working folder.

  1. Create (and test) the JavaScript function and function call that you want the behavior to insert.

  2. The first step in creating a successful behavior is writing and testing a stable, functional script for the behavior to insert into a user document. This file is where you will do just that—it isn't going to be the behavior file, so save it in your working folder, not the Development folder. Call it resize400_test.html.

    The document head should include a JavaScript function for resizing the window and also should include a function call from within the body. The code should look like this:

    <html>
    <head>
    <title>Testing Resize Script</title>
    <script language="JavaScript">
    function resizeTo400() {
    	window.resizeTo(400,400);
    }
    </script>
    </head>
    <body>
    <a href="#" onMouseUp=" resizeTo400()"> Click me!</a>
    </body>
    </html> 

    TIP

    When writing JavaScript functions to be used as behaviors, you don't have to worry about adding the lines of code that will hide the script from older browsers. Dreamweaver will add those lines of code automatically when your behavior is applied.

  3. Test your behavior in a browser (or two). Open the test file in a browser and click on the test link. The window should resize.

  4. If there's a problem, go back to the code and do some troubleshooting until the window resizes. The script needs to work before the behavior that inserts it will work. For best results, of course, try the behavior in several major browsers before declaring it "well-behaved."

  5. Create a basic behavior file, with all structural elements in place. Create a new HTML file. This will be the behavior file, so save it in the Development folder in the Actions folder. Call it Resize400.html.

  6. Start by entering the framework code, as shown in Figure 22.16. Then add your newly devised function and function call in the appropriate places. Your final code should look like this (elements that have been customized from the basic framework are shown in bold):

    <html>
    <head>
    <title>Resize Window to 400</title>
    <script language="JavaScript">
    function resizeTo400() {
    	window.resizeTo(400,400);
    }
    function behaviorFunction() {
    	return "resizeTo400";
    }
    function applyBehavior() {
    	return "resizeTo400()";
    }
    ]
    </head>
    <body>
    <table width="200">
    	<tr>
    		<td>This behavior will resize the user's browser window to 400 pixels wide and 400 pixels high.</td>
    	</tr>
    </table>
    </body>
    </html>
  7. Relaunch Dreamweaver. If Dreamweaver is currently running, quit the program. Then launch the program again so that the new behavior loads.

  8. Create another HTML test file. Call it resize400_behavior_test.html and save it in your working folder. In the new file, create another simple text link (linking to #), just like the first test file. Don't add any JavaScript to this file.

  9. Your code for the new file should look like this:

    <html>
    <head>
    <title>Testing Resize Behavior</title>
    </head>
    <body>
    <a href="#">Click me!</a>
    </body>
    </html>
  10. Open the new test file in Dreamweaver and apply your new behavior. When the file is open in Dreamweaver, try to apply your behavior the same way you'd apply any behavior, by selecting the linked text and clicking the + in the Behavior panel. The new behavior should now appear in the behaviors list, under the Development submenu, as shown in Figure 22.18. The dialog box shown in Figure 22.18 should appear when you choose the behavior.

Figure 22.18 The various interface elements for the Resize Window behavior: the behaviors list, with Development submenu and behavior's menu entry, and the resulting dialog box.

If there's a JavaScript syntax error in your behaviors file, Dreamweaver will give you an error message as soon as you click the + in the panel. Examine the message and see if you can fix the code.

If there are no syntax errors, you'll be allowed to choose and apply your behavior. But this doesn't mean that the code got inserted correctly.

  1. Examine the file's HTML source code to see if the script got properly inserted. Open Dreamweaver's Code Inspector and take a look at the code. It should look just the same as the code you entered yourself, back in step 1 in Exercise 22.8.

  2. If it doesn't, you'll need to do some troubleshooting. Look for the differences between the inserted code and the original, hand-entered code. Then examine your behavior file. Find how the two correlate, and adjust the behavior file. Then try the behavior again.

  3. Test the inserted behavior in a browser. In a browser, repeat the test that you performed on the original code back in step 3 in Exercise 22.8. The JavaScript should work just as well as the code you entered by hand. You've made a behavior!

Exercise 22.9 Adding Arguments to the Function Call

In this exercise, you'll build on the previous behavior. Instead of inserting a script that always resizes the window to the same dimensions, you'll insert a script that asks the user for a desired width and height and then resizes the window to those dimensions. To accomplish this, you'll need to add a form to the behavior file's body and do some fancier scripting in the applyBehavior() function. As in the previous exercise, you'll start by using your test file to create a working version of the function and the function call that you want to insert.

  1. Open resize400_test.html and alter the code so that the function call passes arguments to the function. If you want to keep your original test file safe from harm, make a copy of it to work on for this exercise. Save the copy as resize_test.html.

  2. When you're done, your code should look something like this:

    <html>
    <head>
    <title>Testing Resize Script</title>
    <script language="JavaScript">
    function resizeBrowserWindow(width,height) {
    	window.resizeTo(width,height);
    }
    </script>
    </head>
    <body>
    <a href="#" onMouseUp="resizeBrowserWindow(400,400)">Click me!</a>
    </body>
    </html>
  3. Test the revised script in a browser. As before, make sure that the behavior works in as many browsers as possible before declaring it seaworthy. If it doesn't work, troubleshoot until it does.

  4. Save the Resize400.html behavior file as Resize.html, and open that file in your text editor.

  5. In the behavior file, change the function to match the revised function developed previously. The <script> tag in the head section of the document should now look like this:

  6. <script language="JavaScript">
    function resizeBrowserWindow(width,height) {
    	window.resizeTo(width,height);
    }
    function behaviorFunction() {
    	return "resizeBrowserWindow";
    }
    function applyBehavior() {
    	return "resizeBrowserWindow()";
    }
    </script>
  7. Delete the contents of the behavior file's body section, to make way for the form you'll be creating in the next step.

  8. In the body section, design and create a form to collect the required information from the user. Your form will need two text fields: one for width and one for height. Code for the new body section of the behavior file might look like this:

  9. <form name="theForm">
    <table>
    	<tr valign="baseline">
    		<td align="left" colspan="2" nowrap> Resize the browser window to these dimensions:</td>
    	</tr>
    	<tr valign="baseline">
    		<td align="right" nowrap>New width:</td>
    		<td align="left">
    			<input type="text" name="width" size="8">
    		</td>
    	</tr>
    	<tr valign="baseline">
    		<td align="right" nowrap>New height:</td>
    		<td align="left">
    			<input type="text" name="height" size="8">
    		</td>
    	</tr>
    </table>
    </form>

    Remember, you can always design the form in Dreamweaver's visual editor, if you want. The form should end up looking something like the one shown in Figure 22.19.

    Figure 22.19 The HTML form for the Resize Window behavior dialog box, as it would appear in Dreamweaver's Layout view and as interpreted by a browser.

  10. Rewrite the applyBehavior() function to return a function call that uses the form information. Remember, the applyBehavior() function needs to return the function call exactly as it will appear in the user's document.

  11. This function's return statement will have to construct the code for your desired function call using concatenation. Your code for the applyBehavior() function should look like this:

    function applyBehavior() {
    	var width=document.theForm.width.value;
    	var height=document.theForm.height.value;
    	return "resizeBrowserWindow(" + width + "," + height + ")";
    }
  12. Reload extensions and try out your new behavior. In Dreamweaver, create another test file with a text link in it. Reload extensions, and try your new behavior. Does it work? Does it insert the proper code? If not, do some troubleshooting.

  13. Refine the dialog box with initializeUI(). Any time there's a dialog box, the local function initializeUI() makes sure that the insertion point lands in a handy place.

  14. In the behavior file, add the function, specifying the width text field as the focus (it's the first field in the dialog box). It should look like this:

    function initializeUI() {
     document.theForm.width.focus();
     document.theForm.width.select();
    }

    Also remember to call the function in the <body> tag. The call will look like this:

    	<body onLoad="initializeUI()">

Exercise 22.10 Adding the canAcceptBehavior() Function

The most powerful use of this function—determining whether a behavior will appear grayed out in the behaviors list—is beyond the scope of this chapter. But you can specify a default event handler to be used with the function call.

  1. Duplicate the behavior file, if you want. If you're afraid of goofing up your lovely working behavior file, make a duplicate of it; remember, though, that you'll have to change the name of the defined function and the page title for the duplicate to work properly.

  2. If you're feeling brave, go ahead and work on the behavior file that you created in the previous exercise.

  3. Add the canAcceptBehavior() function to the head of the file, specifying whatever event handler you want the behavior to use.

  4. This one's pretty simple. Just add the following code somewhere inside the <script> tags in the document's head section:

    function canAcceptBehavior() {
    return ("onMouseUp");
    }
  5. Test your revised behavior. You know the drill: Make a test file, reload extensions, and apply the behavior. Examine the code inserted by the revised behavior; the function call should now look like this:

  6. <a href="#" onMouseUp="resizeBrowserWindow(300,300)"> click me </a>

Exercise 22.11 Creating a Separate JS File

Before you can add the finishing touches to your behavior, you'll need to separate it into an HTML file and a JS file, like you did with Contact Info object.

  1. Make a backup copy of Resize.html, just in case. Store the backup outside the Configuration folder, in your working folder.

  2. Move the JavaScript functions into an empty text file. Open Resize.html in your text editor. Select everything between the opening and closing script tags, in the head section.

  3. Cut them to the Clipboard. Then create a new, empty text file and paste them into it. The pasted code should look like this:

    function resizeBrowserWindow(width,height) {
    	window.resizeTo(width,height);
    }
    function behaviorFunction() {
    	return "resizeBrowserWindow";
    }
    
    function applyBehavior() {
    	var width=document.theForm.width.value;
    	var height=document.theForm.height.value;
    	return "resizeBrowserWindow(" + width + "," + height + ")";
    }
    
    function canAcceptBehavior() {
    return ("onMouseUp");
    }
    
    function initializeUI() {
     document.theForm.width.focus();
     document.theForm.width.select();
    }
  4. Save the new file into the Development folder. Call it Resize.js. Remember, recommended practice is to name the HTML and JS files identically and to store them in the same folder.

  5. In Resize.html, add a link to the JS file. Add the link to the <script> tags where you removed the functions. Your <script> tags should now look like this:

  6. <script src = "Resize.js"></script>
  7. Reload extensions, and try out your new behavior. As long as all your copying, pasting and linking was correct, the behavior should function the same as it did before. (If it doesn't, check your code.)

  8. From now on, when you have function changes, you'll change the JS file. The HTML file needs changing only if you update the form, add another function call to the body tag, or add another script tag (you'll be doing that in the next exercise).

Exercise 22.12 Adding the inspectBehavior() Function

What's the point of this function? Try this: In Dreamweaver, create a test file and apply your behavior. Then take a look at the Behavior panel, where you should see the behavior listed along with its event handler. Double-click the behavior to see and possibly change its parameters.

When the dialog box comes back up, it's empty, as shown in Figure 22.20. Dreamweaver has not retrieved the values that you originally entered into the dialog box, so you have no way of knowing what they are unless you look at the source code.

Figure 22.20 Editing a behavior that has no inspectBehavior() function.

Does this strike you as a real shortcoming? The purpose of this exercise is to fix that problem, by collecting the information from the function call that has been inserted and repopulating the dialog box with that information.

  1. Duplicate the behavior files, if you want. Again, if you're afraid of goofing up your existing behavior files, make a backup copy of them, stored in your working folder.

  2. In Resize.html, link the behavior file to the string.js file.

  3. Dreamweaver's Configuration folder contains a bunch of helpful all-purpose JavaScript functions in JS files, ready for you to use in your extension files. You can check them out—they're all in the Configuration/Shared folder. The file that you're going to link to is called string.js—it's in the Shared/MM/Scripts/CMN folder. This file contains several functions for working with strings. It makes the inspectBehavior() function much easier to script.

    To link your behavior file to this JS file, you'll need to add another script tag to the head section of the HTML file, this one containing the relative address of string.js. Your code for the head section of the HTML file should now look like this:

    <head>
    <title>Resize Window</title>
    <script src="Resize.js"></script>
    <script src="../../../Shared/MM/Scripts/CMN/string.js"></script>
    </head>

    Why did you do this? Because the function you're going to write next (in your JS file) is going to call on several functions from the shared JS file, and these links will allow the two JS files to communicate.

  4. In Resize.js, enter the basic framework of the inspectBehavior() function. Start by adding this framework code:

  5. function inspectBehavior(resizeFunctionCall) {
    }

    This part of the code collects the function call that the behavior had earlier inserted into the user's document, for inspection. Dreamweaver automatically submits the inserted function call as an argument to the inspectBehavior() function; you just have to enter some sort of argument name, such as resizeFunctionCall (or any other name you like).

  6. Extract the arguments from the inserted function call.

  7. Simply by declaring the function, you have collected the inserted function call as a string; now you need to extract the parts of that string that correspond to each argument. This requires some fairly fancy scripting involving substrings—but this is why you linked to the string.js file. That file contains the extractArgs() function, which, when passed a function call, extracts the arguments and returns them as an array. Now all you need to do is pass your collected function call to the extractArgs() function, create an empty array, and feed the return statement from that function into it. The added code looks like this:

    function inspectBehavior(resizeFunctionCall) {
     var argArray = new Array;
     argArray = extractArgs(resizeFunctionCall);
    }
  8. Use the extracted arguments to repopulate the form (dialog box).

  9. Your new array, argArray, now contains an element for each argument in the function call. In the array, argArray[0] contains the function call itself. The arguments start at argArray[1]; for your behavior, this means that argArray[1] contains the new width of the resized window the behavior is creating, and argArray[2] contains the new height. Because there are only those two arguments in the inserted function call, there are no more elements to the array.

    All you need to add now is the code that assigns each array element back into its original form element. For your behavior, the code you need to add looks like this:

    function inspectBehavior(resizeFunctionCall) {
     var argArray = new Array;
     argArray = extractArgs(resizeFunctionCall);
     document.theForm.width.value = argArray[1];
     document.theForm.height.value = argArray[2];
    }

    That's it! You now have a complete inspectBehavior() function. Your completed code for the behavior should look like that shown in Figures 22.21 and 22.22.

    Figure 22.21 Complete code for Resize.html, with all links in place.

  10. Try out the revised behavior. Reload extensions in Dreamweaver and create another test file. Because the code changes are now being made to an external .js file, you can actually use your old test file. Apply the behavior, adding whatever width and height values you like; then try double-clicking its name in the Behavior panel. If everything is working properly, the dialog box should open up with those values in place (see Figure 22.23).

  11. If you have a syntax error, you'll get an error message.

    If you didn't correctly link to the string.js file, Dreamweaver will bring up an error message saying that extractArgs() has not been defined.

    If you didn't access the array correctly, the dialog box will open with the wrong values in the wrong places, or with empty text fields, or with "Undefined" showing up in one or more text fields.

    If any of these things happen, check and tweak until it works.

Figure 22.22 Complete function code for Resize.js, with the inspectBehavior() function in place.

Figure 22.23 Editing a behavior that has a properly defined inspectBehavior() function.

NOTE

You have seen that extension files should work the same whether the JavaScript code is embedded in the HTML file or is placed in a separate JS file. One exception to this: In behaviors, when linking to shared files (such as string.js), on some platforms the behavior will not work correctly unless the functions are placed in a separate JS file, as you have done here.

Building Your Own Behaviors

If you've completed all the exercises here, you have the foundation skills to create successful Dreamweaver behaviors. You've also seen that there's a lot more to learn and a lot more that you can do with behaviors. To extend your behavior-making power, check out the Extending Dreamweaver manual, examine existing behavior files, and take a closer look at the shared files, such as string.js—these are all valuable resources.

As with objects, though, you should begin by examining your needs. Although it is tempting to create the biggest, baddest behavior on the block—inserting scripts that make browser windows quake and multimedia pour from the computer—it's often the simple, workhorse JavaScript tasks that will give you the most mileage. What JavaScript functionality do you often wish you had quick access to, but don't? Are there existing Dreamweaver behaviors that you wish operated just a little differently? Ask yourself these questions as you work, and you'll soon know what custom behaviors you'll want to add.

  • + Share This
  • 🔖 Save To Your Account