Dropdown with jQuery

Asked

Viewed 2,688 times

3

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

Jsfiddle

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

Any idea what it might be?

1 answer

2


You can change your logic a little bit to make sure he looks for others dropdown and not only the.

It could be so:

(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>
<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>
<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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.