Dynamic Generation of Menu Structures and JavaScript Rollovers in PHP - The power of repetition (
Page 4 of 6 )
Computers sure do
tolerate repetitive counting tasks a lot better than I do, and PHP takes maximum
advantage of that by allowing stepping through each part of the $SITE_PAGES
array, generating the necessary pointers for the JavaScript, as well as the
appropriate buttons and links to other pages.
Once the basic page layout
and JavaScript are set up, setting up the automation is pretty much a matter of
echoing either a numeric value (in the case of JavaScript pointers) or part of
an array (in the case of links to other pages in the menu).
Replacing a
few lines of the JavaScript shown earlier with some PHP yields this
code:
<script language="JavaScript">
<!-- This script controls the rollovers in the menu area
if (document.images) {
<?
// Changed code begins here!
$counter = sizeof($site_pages);
$i = 0;
do {
$item = $i + 1;
echo " image" . $item . "off = new Image();\n";
echo " image" . $item . "off.src = \"$site_pages[$i]-off.gif\";\n";
echo " image" . $item . "on = new Image();\n";
echo " image" . $item . "on.src = \"$site_pages[$i]-on.gif\";\n";
echo " otherImage" . $item . " = new Image();\n";
echo " otherImage" . $item . ".src = \"$site_pages[$i]-b.gif\";\n";
echo "\n";
$i++;
} while ($i < $counter);
// Changed code ends here!
?>
otherImageDefault = new Image();
otherImageDefault.src = "default.gif";
}
function changeImages() {
if (document.images) {
for (var i=0; i<changeImages.arguments.length; i+=2) {
document[changeImages.arguments[i]].src =
eval(changeImages.arguments[i+1] + ".src");
}
}
}
// -->
</script>
Line 7 gets the number of items in the array
$SITE_PAGES (which is defined in PAGES.HTML) and assigns it to a counter used in
the DO loop defined in lines 10 through 23. Line 11 assigns the $ITEM variable
in order to allow us to start the JavaScript definitions at 1 instead of 0. Line
21 increments the place holder variable $I.
During the development of
this project, some limitations of the PHP parser were encountered, but fixed
with the "." (string concatenation) command used in the echo lines. Without this
workaround, the code would have read:
echo "image$itemoff = new Image();\n";
which PHP (understandably) chokes on. Whenever you use
variables that are embedded in the middle of other text, it's best to use the
"." command to tie things together rather than relying on the PHP parser to
figure out what you want.
The rest of the JavaScript remains the same
because the other items only need to be defined once, and there's no practical
reason to embed it within PHP.