1

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/

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you kind sir. Your advanced example helped me as well.:)
Can you please "translate" to me this piece of code var className = subMenu.className.indexOf('active') !== -1 ? 'menu' : 'menu active'; I'm sensing it's a shorthand for if-then-else statement, but I can't seem to get the longhand version to work.
subMenu.className.indexOf('active') !== -1 checks is current submenu className contains active substring (so it's menu active, then indexOf returns not -1, but index of "active" occurrence). In this case className is set to menu, and since submenu is no longer active it's hidden, because it's was for active class that showed a menu with display: block.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.