The most basic way of making web pages dynamic is to display or hide content
based on some user action. Dynamic HTML forms could be done this way.
The javascript sample presented here will allow you to show or hide any element of the web page (or even an DIV or SPAN element containing parts of HTML document).
Assign an id to web page element you wish to show and/or hide. (for example, to an absolutely-positioned DIV on the page as shown in script demo section).
If you want your element to be initally invisible, have it with style display:none.
<script type="text/javascript"><!--
/* Script by: www.jtricks.com
* Version: 20090221
* Latest version:
* www.jtricks.com/javascript/blocks/showinghiding.html
*/
function showPageElement(what)
{
var obj = typeof what == 'object'
? what : document.getElementById(what);
obj.style.display = 'block';
return false;
}
function hidePageElement(what)
{
var obj = typeof what == 'object'
? what : document.getElementById(what);
obj.style.display = 'none';
return false;
}
function togglePageElementVisibility(what)
{
var obj = typeof what == 'object'
? what : document.getElementById(what);
if (obj.style.display == 'none')
obj.style.display = 'block';
else
obj.style.display = 'none';
return false;
}
//--></script>
Use showPageElement()function with with the object or its
id to show an element of the web page. Similarly, use hidePageElement() to hide and
togglePageElementVisibility() to change it visibility from hidden to shown and vice versa. For example:
<button
onclick="showPageElement('div1')">
Show DIV
</button>
or
<button
onclick="hidePageElement(document.getElementById('div1'))">
Hide DIV
</button>
or (if you require graceful degradation when the browser has javascript turned off - note the presence of return keyword)
Be sure to verify page design with the Javascript turned off.
Browser compatibility
The javascript snippet above was tested on the following user agents:
Mozilla
Firefox 3.0.x
Ok.
Firefox 2.0.x
Ok.
Firefox 1.5
Ok.
Firefox 1.0.x
Ok.
Microsoft
Internet Explorer 7.0
Ok.
Internet Explorer 6.0
Ok.
Internet Explorer 5.0
Ok.
Opera
Opera 9.x
Ok.
Opera 8.x
Ok.
KHTML
Safari 3.2.1 for Windows
Ok.
Konqueror 3.5.5
Ok.
No Javascript or Javascript turned off
Any
Graceful degradation possible. *
*: Graceful degradation could be done if the script is called from
onclick handler of hyperlinks or form submit buttons and
the handler returns false. This way if javascript is turned on, it will stop the
default action (hyperlink navigation or form submit) and execute the script, but
if javascript is turned off default action will execute.