I am having some issue getting a menu to .hide() after clicking on an element.
$(document).on("click", "div.dropdown", function() {
$(this).find("ul").show(0, function() {
$(this).find("li").click(function() {
var a = $(this).html();
$(this).parent().parent().find(".dropdown-title p").html(a);
$(this).parent().hide(); //Onclick won't hide the UL
});
$(this).mouseleave(function() {
$(this).hide();
});
});
return false;
});
div.dropdown {
margin: 0 20px 0 0;
float: left;
border-radius: 3px;
background: rgba(0, 0, 0, .1);
height: 50px;
line-height: 50px;
color: #999;
text-transform: uppercase;
position: relative;
}
div.dropdown div.dropdown-title {
padding: 0 20px;
display: inline-block;
cursor: pointer;
}
div.dropdown div.dropdown-title p {
margin: 0 20px 0 0;
float: left;
font-size: 12px;
}
div.dropdown div.dropdown-title span {
float: left;
}
div.dropdown ul {
position: absolute;
top: 50px;
left: 0;
width: 200px;
overflow-y: auto;
overflow-x: hidden;
border-radius: 0 0 3px 3px;
z-index: 1001;
border: 1px solid #ccc;
list-style-type: none;
padding: 0;
margin: 0;
}
div.dropdown ul li {
line-height: 32px;
background: #fff;
color: #999;
font-size: 12px;
white-space: nowrap;
text-transform: uppercase;
padding: 0 20px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdown">
<div class="dropdown-title">
<p>Sort By</p>
<span><i class="fa fa-caret-down" aria-hidden="true"></i></span>
</div>
<ul style="display: none;">
<li>Option 1</li>
<li>Option 2</li>
<li>Option 3</li>
<li>Option 4</li>
<li>Option 5</li>
<li>Option 6</li>
<li>Option 7</li>
<li>Option 8</li>
</ul>
</div>
I am attempting to get the dropdown menu (the ul element) to .hide() when you click on one of the li elements in the menu, as well as when you mouseleave from the ul. Right now, just the mouseleave portion works and not when you click on one of the li elements. I am unsure of what I am overlooking, so if you see any errors or issue please let me know.
div.dropdownyou show theulwhich is within thediv.dropdown. When you click on a ul item in the menu it run both the code$(this).parent().first().hide();AND$(this).find("ul").show(0, function() {as clicking on theulwill fire thediv.dropdownclick handler. Hope that helps.F12and view console output.