PDA

View Full Version : Hide list item when another is selected



billyboy
11-27-2006, 12:05 PM
This bit of javascript almost does what I want. It toggles the display of submenus when a list item is clicked. What I would also like is to hide the submenu that is showing when another selection is made. I just can't figure out how, and would appreciate some help.

function toggle() {
var el=document.getElementById("menu").getElementsByTagName("li");
for (i=0; i<el.length; i++) {
el[i].className = "hide";
el[i].onclick = function() {
this.className = (this.className == "hide") ? "show" : "hide";
}
}
}
Then in the CSS I have defined the properties for the classes to hide the submenus until selected, and the markup is just a series of nested uls with the top level ul given the id "menu".

Also I was wondering if its possible to make it work on mouseover/mouseout as well as onclick.

mwinter
11-27-2006, 04:59 PM
Then in the CSS I have defined the properties for the classes to hide the submenus until selected, and the markup is just a series of nested uls with the top level ul given the id "menu".

How deeply nested are these lists?

The most elegant solution is to retain a reference to the "expanded" list. This is trivial for only one "level", but slightly - and only slightly - more involved for multiple levels.



Also I was wondering if its possible to make it work on mouseover/mouseout as well as onclick.

Sure, but one thing at a time. :)

Mike

billyboy
11-28-2006, 06:01 PM
Hi Mike, thanks for the response.

If possible I'd like something that's adaptable to different situations, that would work regardless of the number of levels of sub menus.

I had been using the following code, which does that. But it doesn't take into account keyboard navigation, so I tried adding functions for onfocus/onblur by copying the existing onmouseover/onmouseout functions. Onblur didn't hide the submenus again though (Am I misunderstanding what onblur does, or was I doing something wrong?) So I tried a different approach and was hoping I could put it all together into one. I got as far as the first code I posted and got stuck:
function hideSubMenus() {
var el=document.getElementById("menu").getElementsByTagName("li");
for (i=0; i<el.length; i++) {
el[i].className = "hide";
el[i].onmouseover = function() {
this.className = "show";
}
el[i].onmouseout = function() {
this.className = "hide";
}
}
}