Jeffson Jeffson - 14 days ago 8
jQuery Question

Jquery - Close dropdown/remove active class when clicking outside or clicking another dropdown

I just created my own jquery plugin and I have a dropdown that toggle the 'active' class when clicking itself

and I just want the 'active' class to be remove when clicking outside of an element or clicking other dropdown
and Every dropdown has different mark-up but with the same class and I initialized them all via jquery by calling :

$('.dropdown').dropdown();


this thing has a similar appearance of Bootstrap dropdown

here's my code :

<style>
.dropdown {
position:relative;
display:inline-block;
}
.dropdown > button {
padding:6px 12px;
border-radius:4px;
border:1px solid #bbb;
background:linear-gradient(#fff 5% , #ddd 100%);
}

.dropdown.active > button,
.dropdown > button:active {
background:#ddd;
box-shadow:inset 0px 3px 6px rgba(0,0,0, 0.125);
}

.dropdown > ul {
margin:0;
list-style:none;
padding:0;
}

.dropdown > .menu {
border:1px solid #ddd;
border-radius:4px;
position:fixed;
top:65px;
display:none;
}
.dropdown > .menu li ,
.dropdown > .menu .item {
padding:6px 12px;
min-width:100px;
font-weight:bold;
}

.dropdown.active > .menu {
-webkit-transform:none;
display:inline-block;
}

</style>


<script>
(function($) {
$.fn.dropdown = function() {
var dropdown = this;
dropdown.find('button').click(function() {
$(this).parent('.dropdown').toggleClass('active');
});

}
})(jQuery);
</script>
<script>
$('.dropdown').dropdown();
</script>


<div class="dropdown">
<button>Open</button>
<div class="menu">
<div class="item">One</div>
<div class="item">Two</div>
<div class="item">Three</div>
<div class="item">Four</div>
<div class="item">Five</div>
</div>
</div>

<div class="dropdown">
<button>Open</button>
<ul class="menu">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
</div>

Answer

You can first close all drop downs expect clicked one, then active/open currently clicked drop down:

var p = $(this).parent();
$('.dropdown').not(p).removeClass('active');

to close drop downs when clicked outside:

$(window).click(function() {
    $('.dropdown').removeClass('active');
});

And to prevent including drop down itself by above code:

$('.dropdown').click(function(event){
    event.stopPropagation();
});

Here is a demo: https://jsfiddle.net/huvzb305/3