Skeets O'Reilly Skeets O'Reilly - 1 month ago 5
CSS Question

Hide CSS dropdown menu with Javascript

I have a dropdown that works with CSS. I want it to disappear when an item in the dropdown is clicked, but still function correctly after words.

Here is what I have so far:



$("span").click(function(){
$(this).parent().hide();
$("#text").html("Try hovering over it again. Now it's broken, because the display attribute was set for the element.");
});

.dropDownContainer{
display: inline-block;
}
.dropDown{
display: none;
padding-left: 6px;
background-color: black;
color:white;
position: absolute;
}

.dropDownContainer:hover .dropDown {
display: block;
}
span{
cursor:pointer;
color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropDownContainer">
hover over this
<div class="dropDown">
this is the dropdown<br><br>

click <span>this</span> to close drop down.
<br><br>
It doesn't work.
</div>
</div>
<div id="text">

</div>




Answer

You should add a timeout to remove the display none right after you hide. so the cursor wont be positioned in a way it will automatically reopen (on hover this) so its fine.

$("span").off().click(function(){
    var dropdown = $(this).parent();
    dropdown.hide();
    setTimeout(function(){dropdown.removeAttr('style');}, 300);
    $("#text").html("Try hovering over it again. Now it's broken, because the display attribute was set for the element.");
});