Recently, I implemented hover and click events to trigger the opening of a dropdown content
The functionality is mostly working as expected but there is a slight issue
When hovering over the element, the content opens and closes properly
However, on the first click, it opens correctly but on the second click, it doesn't close immediately, requiring me to exit the hover state to see the effect of the second click
Here is the HTML structure:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<style>
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
padding: 12px 16px;
z-index: 1;
}
.dropdown:hover .dropdown-content {
display: block;
}
.openCont{
display:block !important;
}
.closeCont{
display: none !important;
}
</style>
</head>
<body>
<h2>Hoverable Dropdown</h2>
<p>Move the mouse over the text below to open the dropdown content.</p>
<div class="dropdown">
<button>Mouse over me</button>
<div class="dropdown-content">
<p>Hello World!</p>
</div>
</div>
<div class="dropdown">
<button>Mouse over me</button>
<div class="dropdown-content">
<p>Hello World!</p>
</div>
</div>
</body>
</html>
And this is the JavaScript function that handles the click event:
$(".dropdown").click(function(){
console.log('toggle')
$(this).find("div.dropdown-content").toggleClass('openCont');
});