I have a div I want to hide when clicking outside it.
It almost works, except the button class is only changing once every two times.
I click on the button, the active button class is added and the dropdown slides down, I click somewhere outside the dropdown, it slides up and the button class returns to it’s original state. BUT, when I repeat this, the button class ‘isActive’ is not added.
Here’s the function:
function toggleSelectGroupList(){
$('#groupListSortby').slideToggle(30);
$('body').click(function(){
$('#groupListSortby').click(function(e) { e.stopPropagation(); })
$('#groupListSortby').hide();
$('.sortFriends .btngrey .gfx').toggleClass('isActive');
$('.sortFriends .btngrey a').toggleClass('isActive');
});
}
Markup:
<div class="sortFriends">
<div class="btngrey">
<span class="gfx"></span>
<a onClick="toggleSelectGroupList()">All friends</a>
</div>
<div class="dropdownList" id="groupListSortby">
<ul>
<li class="isActive">
<span class="gfx"></span>
<a href="#">All friends</a>
</li>
<li>
<a href="#">Recently added</a>
</li>
<li class="last">
<a href="#">The Railers</a>
</li>
</ul>
</div>
</div>
You should bind your
clickhandlers from the beginning, and the propagation stop should be immediately bound as well, like this overall:To match, your
<a>shouldn’t have anonclickinline with this anymore, just this will do:You can test it out here.