If you want to hide the menu after clicking on the link, with CSS you won’t be able to. You have to hide the menu inside the event that captures the click on the menu links:
$(".dropdown-menu li a").on("click", function(e){
e.preventDefault(); // cancela o evento do click
$(".dropdown-menu")
.hide() // esconde todos os menus
.delay(100) // dá um atraso de 100ms
.fadeOut(10, function(){ // fadeOut com callback para remover o display
$(this).css("display", ""); // remove o display
});
});
The .hide()
will hide the menu, but it adds an attribute style="display: none;"
to the element, and thereby the :hover
CSS will no longer work because the attribute style
is stronger than the CSS rules. That’s why you need to remove display: none;
of style
added; or can remove itself style
if the widget does not have it. Just swap the line:
$(this).css("display", "");
For:
$(this).removeAttr("style");
Using events mouseenter
and mouseleave
The above way works well in some browsers, but gives problem in others (such as Edge and IE11). In these browsers (including the snippet here and in Jsfiddle), when the menu is hidden, the mouse cursor is still active over the link (maybe a bug) causing the menu to appear again.
A more functional way would be to use the above events in place of CSS :hover
:
$(".dropdown").on("mouseenter mouseleave", function(e){
$(".dropdown-menu", this)[e.type == "mouseenter" ? "show" : "hide"]();
});
$(".dropdown-menu li a").on("click", function(e){
e.preventDefault(); // cancela o evento do click
$(".dropdown-menu")
.hide() // esconde todos os menus
});
.dropdown-menu{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dropdown">
Menu1
<ul class="dropdown-menu">
<li><a href="">op1</a></li>
<li><a href="">op2</a></li>
</ul>
</div>
<div class="dropdown">
Menu2
<ul class="dropdown-menu">
<li><a href="">op1</a></li>
<li><a href="">op2</a></li>
</ul>
</div>
When taking the mouse over the element
.dropdown
Hover should be canceled. If this is not happening, probably some Javascript code is forcing the menu to stay active.– Sam
This happens, @Sam. But, I want it to disappear immediately after the click.
– neves
Put the function that opens the page when a menu item is clicked. I think the problem and the solution is in it.
– Sam