Dropdown with jQuery

3

I was looking for a dropdown menu with jQuery and found this example:

JSFiddle

It opens and closes normal when I click outside the menu or some item of it, except when I open another dropdown.

Any idea what it might be?

    
asked by anonymous 02.04.2017 / 06:03

1 answer

2

You can change logic a bit to make sure it looks for the other dropdown and not just itself.

It could look like this:

( jsFiddle )

$(document).click(function(e) {
    var target = e.target;
    $('.dropdown-menu').each(function() {
        var $this = $(this);
        var dropdown = $this.prev('.dropdown');
        if (dropdown[0] == target) $(this).toggle();
        else $(this).hide();
    });
});
.btn-group {
    position: relative;
    display: inline-block;
    font-size: 0;
    vertical-align: middle;
}

.btn-group + .btn-group {
    margin-left: 16px;
}

.btn-group > .dropdown-menu {
    list-style-type: none;
    z-index: 1000;
    display: none;
    position: absolute;
    top: 100%;
    left: 0;
    padding: 4px 0;
    margin-top: 3px;
    min-width: 160px;
    font-size: 14px;
    border: 1px solid #ccc;
    background-color: #fff;
}

.btn-group > .dropdown-menu li a {
    display: block;
    padding: 3px 12px;
    text-decoration: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="btn-group">
    <button class="dropdown">Select</button>
    <ul class="dropdown-menu">
        <li><a href="javascript:void(0)">Action 1</a></li>
        <li><a href="javascript:void(0)">Action 2</a></li>
        <li><a href="javascript:void(0)">Action 3</a></li>
    </ul>
</div>
<div class="btn-group">
    <button class="dropdown">Select</button>
    <ul class="dropdown-menu">
        <li><a href="javascript:void(0)">Action 1</a></li>
        <li><a href="javascript:void(0)">Action 2</a></li>
        <li><a href="javascript:void(0)">Action 3</a></li>
    </ul>
</div>
    
02.04.2017 / 07:37