| home / programming / javascript / mozillaapps / chap5 / 2 | [previous] [next] |
|
|
Using the createElement method in XUL lets you accomplish things similar to document.write in HTML, with which you can create new pages and parts of a web page. In Example 5-9, createElement is used to generate a menu dynamically.
Example 5-9: Dynamic menu generation
<?xml version="1.0"?>
<?xml-stylesheet href="test.css" type="text/css"?>
<!DOCTYPE window>
<window id="test-win"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
title="test"
style="
min-width : 200px;
min-height: 200px;">
<script>
<![CDATA[
function generate( ){
var d = document;
var popup = d.getElementById('menupopup');
var menuitems = new Array('menuitem_1',
'menuitem_2', 'menuitem_3',
'menuitem_4', 'menuitem_5');
var l = menuitems.length;
var newElement;
for(var i=0; i<l; i++)
{
newElement = d.createElement('menuitem');
newElement.setAttribute('id', menuitems[i]);
newElement.setAttribute('label', menuitems[i]);
popup.appendChild(newElement);
}
return true;
}
]]>
</script>
<menu label="a menu">
<menupopup id="menupopup">
</menupopup>
</menu>
<spacer flex="1" />
<button id="ctlbutton" class="testButton" label="generate" oncommand="generate( );" />
</window>
The JavaScript function generate( ) in Example 5-9 gets the menupopup as the parent element for the new elements, creates five menuitems in an array called menuitems, and stores five string ID names for those menuitems.
The variable l is the length of the array. The variable newElement is a placeholder for elements created by using the createElement method inside of the for loop. generate( ) assigns newElement on each iteration of the loop and creates a new menuitem each time, providing a way to dynamically generate a list of menu choices based on input data or user feedback. Try this example and experiment with different sources of data, such as a menu of different auto manufacturers, different styles on group of boxes that come from user selection, or tabular data in a tree.
| home / programming / javascript / mozillaapps / chap5 / 2 | [previous] [next] |
Created: September 26, 2002
Revised: September 26, 2002
URL: http://webreference.com/programming/javascript/mozillaapps/chap5/2/4.html