Reputation: 847
I got this dropdown menu which works, but I would also like it to close when I click outside it… I've tried some answered solutions but something's wrong and I can't figure it out..Could someone point what am I missing out here? Thanks a lot
$("#toggle").on('click', function() {
$(".dropdown").toggleClass("dropdown--visible");
});
$(document).click(function(){
$(".dropdown").hide();
});
$(".dropdown").click(function(e){
e.stopPropagation();
});
.dropdown {
background: red;
display: none;
}
.dropdown--visible {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="toggle">Toggle dropdown</button>
<div class="dropdown">
<ul>
<li>one</li>
<li>two</li>
</ul>
</div>
Upvotes: 2
Views: 303
Reputation: 306
You have setup a click event listener for document and it will execute all the time when you click anywhere. You can use a common class to filter out the dropdown events.
<button id="toggle" class="dd">Toggle dropdown</button>
<div class="dropdown dd">
<ul>
<li>one</li>
<li>two</li>
</ul>
</div>
$(document).click(function(e){
if (!$(e.target).hasClass('dd')) {
$(".dropdown").removeClass("dropdown--visible");
}
});
Also better use removeClass() without using hide() since hide() adds a display:none; directly to the element and will be hard to control.
Upvotes: 2
Reputation: 4226
This vanilla-flavored solution uses a handleDropdown
function that checks two conditions:
- Was the toggle button clicked?
- Is the dropdown currently hidden?
If both are true, it shows the dropdown. Otherwise, it hides the dropdown.
const dropdown = document.getElementsByClassName("dropdown")[0],
toggle = document.getElementById("toggle");
document.addEventListener("click", handleDropdown);
function handleDropdown(event){
if(event.target == toggle && dropdown.style.display != "block"){
dropdown.style.display = "block";
}
else{
dropdown.style.display = "none";
}
}
.dropdown {
background: red;
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="toggle">Toggle dropdown</button>
<div class="dropdown">
<ul>
<li>one</li>
<li>two</li>
</ul>
</div>
Upvotes: 1
Reputation: 33
$("#toggle").on('blur click', function() {
$(".dropdown").toggleClass("dropdown--visible");
});
$(document).click(function(){
});
.dropdown {
background: red;
display: none;
}
.dropdown--visible {
display: block!important;
}
.dropdown--invisible {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="toggle">Toggle dropdown</button>
<div class="dropdown">
<ul>
<li>one</li>
<li>two</li>
</ul>
</div>
Upvotes: 2