All it takes is changing the display CSS property. Setting display: block; (the default for div tags) makes it visible, and display: none; makes it hidden. The advantage to using display is that other items on the page will move to close the void left by the hidden object.
Fist, we'll start with creating the function:
Code: Select all
function toggleDisplay(id) {
}
Code: Select all
function toggleDisplay(id) {
var obj = document.getElementById(id);
}
Code: Select all
function toggleDisplay(id) {
var obj = document.getElementById(id);
if(obj.style.display == 'none') {
// show the object
} else {
// hide the object
}
}
Code: Select all
function toggleDisplay(id) {
var obj = document.getElementById(id);
if(obj.style.display == 'none') {
obj.style.display = 'block';
} else {
obj.style.display = 'none';
}
}
Now to use it, we just need to call the function with a link, button, or any event. For example:
Code: Select all
<div id="div">Test Object</div>
<a href="#" onClick="toggleDisplay('div'); return false;">Show/Hide</a>
Here is the whole example page:
Code: Select all
<html>
<head>
<title>Toggle Display</title>
<script type="application/javascript" language="javascript">
function toggleDisplay(id) {
var obj = document.getElementById(id);
if(obj.style.display == 'none') {
obj.style.display = 'block';
} else {
obj.style.display = 'none';
}
}
</script>
</head>
<body>
<div id="div">Test Object</div>
<a href="#" onClick="toggleDisplay('div'); return false;">Show/Hide</a>
</body>
</html>