Codemon
Codemon

Reputation: 369

Simple dropdown menu with javascript

I am new at javascript and I can't seem to get this simple dropdown menu to work. This is what I have done so far :

Html code:

    <ul>    
        <li onClick='showMenu()'>
            <a href="#" >Birds</a>
            <ul class="menu">
                <li><a href="">Ratites</a></li>
                <li><a href="">Fowl</a></li>
                <li><a href="">Neoaves</a></li>
            </ul>
        </li>
   </ul>

CSS code:

a {
    color: #06c;
}

ul {
    padding: 0;
    margin: 0;
    background: pink;
    float: left;
}

li {
    float: left;
    display: inline;
    position: relative;
    width: 150px;
    list-style: none;
}

.menu {
    position: absolute;
    left: 0;
    top: 100%;
    background: #ccc;
    display: none;
}

Javascript code:

 function showMenu(){
       document.getElementByClass("menu").style.display="block";
 }

My javascript code isn't working. Why won't my nested list show when I click? Here is a jsfiddle link to my code: http://jsfiddle.net/wkmd7h0r/13/

Upvotes: 1

Views: 1380

Answers (1)

dfsq
dfsq

Reputation: 193261

It's getElementsByClassName not getElementByClass. Fixed code:

function showMenu() {
     document.getElementsByClassName("menu")[0].style.display = "block";
}

Also getElementsByClassName returns a NodeList collection, so you should use [0] to get the first element in this collection.

Demo: http://jsfiddle.net/wkmd7h0r/14/

Here is an example of more advanced functionality with addEventListener.

Upvotes: 4

Related Questions