TheMan TheMan - 5 months ago 8
Javascript Question

Drop down menu only by click on button

I try to make a drop down menu, but I want to drop down just click on the button "children". Currently drop down even when I click on one of the names. How to fix it?

Fiddle here - http://jsfiddle.net/cRsZE/1378/

Thanks for your help!

<ul id="nav">
<li class="parent"><button>Childrens</button>
<ul class="sub-nav">
<li>Johnny</li>
<li>Julie</li>
<li>Jamie</li>
</ul>
</li>
</ul>

Answer

Change your selector from $('.parent') to $('.parent button'):

$(document).ready(function() {
    $('.parent button').click(function() {
        $(this).next('.sub-nav').toggleClass('visible');
    });
});
#nav {
    list-style: none;
    padding: 0;
    margin: 0;
}
#nav > li {
    display: inline-block;
    vertical-align: top;
    position: relative;
}
#nav ul.sub-nav {
    position: absolute;
    min-width: 200px;
    display: none;
    top: 100%;
    left: 0;
}

#nav ul.visible {
    display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="nav">
    <li class="parent">
        <button>Childrens</button>
        <ul class="sub-nav">
            <li>Johnny</li>
            <li>Julie</li>
            <li>Jamie</li>
        </ul>
    </li>
    <li class="parent">
        <button>Childrens</button>
        <ul class="sub-nav">
            <li>Johnny</li>
            <li>Julie</li>
            <li>Jamie</li>
        </ul>
    </li>
</ul>

Comments