Reputation: 489
I have a dropdown menu that has display: none
and when hovering on parent it has display: block
via CSS. The dropdown menu links to anchors on the same page, so when I click I want the dropdown to disappear so I have on click
$('.dropdown-menu').css("display", "none")
However, the jquery has now overridden the display: block
that happens on hover. How can I keep the previous functionality while hiding the menu when clicking?
Upvotes: 1
Views: 1700
Reputation: 478
Best then to use jQuery for hover and click actions.
Here it is quick solution:
// menu hover
$(".dropdown").mouseover(function() {
$('.dropdown-content').css("display", "block");
})
.mouseout(function() {
$('.dropdown-content').css("display", "none");
});
//menu click
$(".dropdown").click(function() {
$('.dropdown-content').css("display", "none");
});
/* Dropdown Button */
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
/* The container <div> - needed to position the dropdown content */
.dropdown {
position: relative;
display: inline-block;
}
/* Dropdown Content (Hidden by Default) */
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
}
/* Links inside the dropdown */
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
/* Change color of dropdown links on hover */
.dropdown-content a:hover {
background-color: #f1f1f1
}
.dropdown:hover .dropbtn {
background-color: #3e8e41;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdown">
<button class="dropbtn">Dropdown</button>
<div class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
Upvotes: 1
Reputation: 1453
I've added another function to show the content again and edited your original a bit.
https://jsfiddle.net/dc38u09p/6/
$(document).on('click', 'a.hide-on-click', function(event) {
$('.dropdown-content').hide();
});
$('.dropdown').on('mouseenter', function(){
$('.dropdown-content').show();
});
Upvotes: 1
Reputation: 1707
Add this into your javascript
$(document).on('mouseover', '.dropdown', function(event) {
$('.dropdown-content').css("display","block");
});
Upvotes: 1