User Guide

140 Chapter 7: Commands
Writing the JavaScript code
The following example consists of two extension API functions,
canAcceptCommand() and
commandButtons(), which Dreamweaver calls, and one user-defined function, changeCase()
which is called from the
commandButtons() function.
canAcceptCommand()
When a user clicks the Commands menu, Dreamweaver calls the
canAcceptCommand() function
for each menu item to determine whether it should be enabled. If
canAcceptCommand() returns
the value
true, Dreamweaver displays the menu item text as active or enabled. If
canAcceptCommand() returns the value false, Dreamweaver dims the menu item.
The first task in creating a command is to determine when the item should be active and when it
should be dimmed. In this example, the menu item is active when the user has selected text in
the document.
The first lines of
canAcceptCommand() retrieve the selected text by retrieving the DOM for the
user’s document and calling the
getSelection() function on the document object. Next, the
function retrieves the node that contains the selected text, followed by any children of the node,
as shown in the following code:
function canAcceptCommand(){
var theDOM = dw.getDocumentDOM(); // Get the DOM of the current document
var theSel = theDOM.getSelection(); // Get start and end of selection
var theSelNode = theDOM.getSelectedNode(); // Get the selected node
var theChildren = theSelNode.childNodes; // Get children of selected node
The last line checks to see if the selection or its first child is text and returns the result as a value of
true or false:
return (theSel[0] != theSel[1] && (theSelNode.nodeType ==
Node.TEXT_NODE || theSelNode.hasChildNodes() && (theChildren[0].nodeType ==
Node.TEXT_NODE)));
The first part of the return statement (theSel[0] != theSel[1]) checks if the user has selected
anything in the document. The variable
theSel is a two-slot array that holds the beginning and
ending offsets of the selection within the document. If the two values are not equal, content has
been selected. If the values in the two slots are equal, there is only an insertion point and nothing
has been selected.