Tuesday, March 03, 2009

Javascript menus

Most websites these dates are built with a database, php or asp.net. In both php and asp.net it is no problem to build a functiion that generates your menu for all your pages. That is nice, because it means you have to maintain your menu only once: when your menu changes, when an exptar page becomes available, you dont have to change tenths of pages, changing just that one module is sufficient.

But there are still numerous websites that are still html/xml, stylesheets and javascript. Of course you can use frames to attain the same effect: simply have 2 frames, a small left one for your menu and a wide right one for you contents. And voila, you have to maintain your menu only once.
But... frames are on the way out.

But for sure, code like:
<pre>
<html>

<frameset cols="180px,50%,180px">
<frame src="frame_a.html" />
<frame src="frame_b.html" />
<frame src="frame_c.html" />
</frameset>

</html>
</pre>
will execute properly in both IE7 en FF3.

You can aslo modify it easily to add a header and footer:
<pre>
<html>

<frameset rows="80px,50%,60px">
<frame src="frame_d.html" />
<frame src="frame_previous.html" />
<frame src="frame_f.html" />
</frameset>

</html>
</pre>

The page "frame_previous.html" refers of course to the previous html page displayed above. The combination gives you a solid layout with header, footer and 3 columns in between.
But as noted, frames are no longer considered sexy, and frames are on the way out. One reason no doubt is that for frames you need DTD "HTML 4.01 Frameset", which is incompatible with say xhtml.

So designers and builders have to look for an alternative. The way to go for layouts are divs. But divs have no includes, and neither has html. There is a way out, however, and that is through javascript. Javascript can be stored in separate javascript files, and included in any html page. Javascript can write html, and we can simply misuse this to have a javascript function which writes a menu in a div.

Example:
menuscript.js:
function WriteMenu()
{
document.write('<a href="Main.html">Main</a><br />');
document.write('<a href="Option1.html">Option 1</a><br />');
document.write('<a href="Option2.html">Option 2</a><br />');
}

demo.html:
<div id='title'>
title
</div>

<div id='left_column'>
WriteMenu();
</div>

<div id='contents'>
contents
</div>

<div id='footer'>
footer
</div>