I\'m in the process of learning Javascript and I\'m trying to create a simple dropdown menu. An example of my desired functionality can be seen on the google homepage in the top
It looks like you have a pretty decent setup as-is. You'll likely run into some event bubbling problems (for more info, take a look at PPK's Event Order Article). That seems to be outside of the scope of your current question, so I'll just give you what you asked for:
hideMenus()
{
var uls = document.getElementsByTagName('ul'), i;
for (i = 0; i < uls.length; i++)
{
if (uls[i].className === 'submenu' && uls[i].style.display !== 'none')
{
uls[i].style.display = 'none';
}
}
}
First, we get all the
There are a couple faults with this code:
class="animal submenu"
), then it will not hide the menugetElementsByClass
.These aren't huge faults, especially if you're only using this to learn about javascript, and if you closely control your code (i.e. no other developers are working on it). All in all, it's a good stepping stone.
In the future, I'd suggest using addEvent
- a fairly common function that allows you to add event handlers to elements without using onclick="..."
. There are a couple different implementations of it, but they (almost) all work the same from your perspective. Here are links to Dean Edwards's Version and John Resig's Version
Good luck!