20.2.2Using a Brush
Unlike a normal XHTML brush, we have to explicitly add the JavaScript snippet to the XHTML output stream. There are essentially four different places a JavaScript snippet can be added: (1) right at the current position in the XHTML output stream into a script
tag, (2) into a method that will be automatically evaluated when the page has completely loaded, (3) to a DOM element, or (4) as an event handler to a DOM element.
1. Adding to a script tag. You can add the brush right at the current place into the XHTML output stream. This is done by creating a script tag using an expression such as html script: aJavaScriptBrush
. This technique is simple and straightforward, however it has the disadvantage that the JavaScript code will be evaluated right away when the web browser parses the file. This might happen even before the whole page is read in the web browser and might cause JavaScript errors, as there are no guarantees that the DOM elements you use are already available. In most cases this is not the preferred way to go.
2. Adding to a list of load-scripts. You can add the brush to a list of load scripts. These load scripts will be evaluated after the page has finished loading. This solution is usually preferred over the previous one. The following expression is an example:
html document addLoadScript: aJavaScriptBrush
3. Adding to a DOM element. Often JavaScript brushes need to know the ID of the element they are supposed to operate on. For example if we want to apply an effect to an element we need to pass the ID of that particular element to the JavaScript brush. Luckily there is an easy way to do this automatically and at the same time add the JavaScript brush to the list of load scripts. Every XHTML brush understands the message script:
which will (1) ensure that tag has an unique ID, (2) pass the ID of the tag to the JavaScript brush, and (3) add the JavaScript brush to the list of load scripts. Here’s an example:
html div script: aJavaScriptBrush; with: 'Hello World'
4. Adding as a DOM event handler. So far the JavaScript code is executed unconditionally when it is encountered or after the page has loaded. Luckily one can assign JavaScript snippets to events on XHTML DOM nodes. Similar to the technique above, a JavaScript snippet that has no specific ID will operate on its owning XHTML element.
The most common events are onclick
and onchange
. For example,
html div onClick: aJavaScriptBrush; with: 'Hello World'
will execute the JavaScript code when the div element is clicked. You can find a full list of DOM events in the table below. Keep in mind that not all events are supported by all XHTML tags. For example the onchange
event will never be triggered on a div tag, since it only applies to form elements that can be changed. The support and handling of some of the events (foremost among these are onblur
, ondblclick
, onfocus
, onload
, and onunload
) differ significantly among the web browser implementations.