john_woo wrote:
Hi,
I'm wondering how to use javascript to do something like:
TOP_Button
when clicking on it, it becomes:
TOP_Button
sub_button_1
sub_button_2
and clicking TOP_Button again, two sub_buttons get hidden.
but clicking on sub_button, it should not be hidden.
If you are trying to create an hierarchical menu system, there are lots
of those around (though they're mostly pretty awful).
<URL:
http://search.atomz.com/search/?sp-q...p=All&sp-k=All
The example below does what you want, you should be able to modify it
fairly easily to use buttons if that's what's really needed.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title> new document </title>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1">
<style type="text/css">
..clickable {
cursor: pointer;
color: #00f;
background-color: #fff;
text-decoration: underline;
}
</style>
<script type="text/javascript">
function initList(id)
{
// Check features before applying modifications
if ( !document.getElementById
|| !document.getElementsByTagName) {
return;
}
// Get the button
var topBtn = document.getElementById(id);
// More feature testing
if (!topBtn.style || !topBtn.parentNode) return;
// Get it's LI parent
var btnParent = getParentByTagName(topBtn, 'li');
if (!btnParent) return;
// Get the first UL child node
var btnSet = btnParent.getElementsByTagName('ul')[0];
// If next test OK, do changes else do nothing
if (btnSet){
topBtn.className = 'clickable';
toggleVis(btnSet);
topBtn.onclick = function(){toggleVis(btnSet);}
}
}
function getParentByTagName(el, nn)
{
nn = nn.toLowerCase();
while (el.parentNode && nn != el.nodeName.toLowerCase() ){
el = el.parentNode;
}
return (nn == el.nodeName.toLowerCase())? el : null;
}
function toggleVis(el)
{
// x introduced to prevent wrapping
var x = el.style;
x.visibility = ('hidden' == x.visibility)? 'visible' : 'hidden';
}
</script>
</head>
<body>
<ul>
<li><span id="topButton">LTOP_Button</span>
<ul>
<li>sub_button_1</li>
<li>sub_button_2</li>
</ul>
</li>
</ul>
<script type="text/javascript">
initList('topButton');
</script>
</body>
</html>
initList could be assigned to the body onload event, however if the
document is large and takes some time to load, the list of buttons might
be displayed for a short time before being hidden.
Putting it where it is means it will run as soon as the relevant
elements have been created. You may also want to look at the CSS
display property which can be toggled between 'none' and '' to hide and
show elements respectively.
--
Rob