This weekend I finished up some code that I’d started a little while ago but hadn’t had the chance to complete: a function, that can be used in the progressive enhancement style, for showing and hiding parts of a web page on demand.


ondemand(elem, showLabel, hideLabel)
  • elem: the element to make on demand (either an element object reference or an id)
  • showLabel: the label for the button to show the element
  • hideLabel: the label for the button to hide the element

The function hides the specified element and inserts a button into the document to show and hide the element again. To use in a progressive enhancement style, include the part of the web page that you’d like to be shown and hidden on demand as static content, and then call the ondemand function on it. If JavaScript is turned off, the content will always be shown and there will be no button to hide or show the content.

Source code


<script type="text/javascript" src="dojo/dojo.js"></script>
<script type="text/javascript" src="ondemand.js"></script>
<script type="text/javascript">
        ondemand("ondemand1", "Show Details", "Hide Details");

<div id="ondemand1">
<form id="form1" action="#">
<p><label for="tags">Tags:</label><br>
<input id="tags" type="text"></p>
<p><label for="description">Description:</label><br>
<textarea id="description" rows="5" cols="30"></textarea></p>
<p><button type="submit">Save</button></p>

Progressive enhancement and flicker

Due to the page being reworked after loading you may see flicker as the content is initially shown and then quickly hidden. One approach for minimizing the flicker is to add a document.write statement that inserts a CSS rule to hide the content to be made on demand before it appears in the document. For example:

document.write('<style type="text/css">#ondemand1 {
    display: none }</style>');

The document will still change after the page is loaded, as the button is inserted, but the change will be smaller than before and it will be additive rather than subtractive.

About me

Simon Bates is a software developer living and working in Toronto.


Created with Jekyll.