I’m trying to close an HTML dropdown list when an option is clicked. The list is displayed on hover using CSS. It disappears OK when the cursor is moved away, but not when an option is clicked.
Here’s a fiddle showing the problem: https://jsfiddle.net/evL5d8aq/
I need the clickable element to be either a DIV or a table cell. The fiddle shows both exhibiting the same problem.
The click event fires OK. I’ve tried a few approaches to close the list but none work satisfactorily, as shown in the comments I’ve added in the JS.
I’m using Bootstrap 4.
HTML:
<table class="table table-bordered">
<tbody>
<tr>
<td class="text-center dropdown custom-dropdown" style="background-color: red">JavaScript
<ul class="dropdown-menu custom-dropdown-list mt-0">
<li class="text-center" style="background-color: lightgreen;">HTML</li>
<li class="text-center" style="background-color: yellow;">CSS</li>
<li class="text-center" style="background-color: lightblue;">C#</li>
</ul>
</td>
</tr>
</tbody>
</table>
<div style="background-color: red" class="text-center dropdown custom-dropdown">
JavaScript
<ul class="dropdown-menu custom-dropdown-list mt-0">
<li class="text-center" style="background-color: lightgreen;">HTML</li>
<li class="text-center" style="background-color: yellow;">CSS</li>
<li class="text-center" style="background-color: lightblue;">C#</li>
</ul>
</div>
JS:
$('.custom-dropdown').on('click', function(e) {
console.log("You selected: " + e.target.innerText)
// Works, but then can't invoke dropdown
//$('.dropdown-menu').css({'display': 'none'});
// Hides the TD or Div as well as the DDL
//$(this).hide();
// Does nothing
$(".custom-dropdown-list").removeClass("open");
});
2
Answers
try toggle –
You should use that code:
And you should add that CSS
And remove CSS related to the hover effect
https://jsfiddle.net/jfagLrxp/23/