skip to Main Content

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


  1. try toggle –

    <script type="text/javascript">$(document).on('click', '.list > li ', function () {
    $(this).next('.list').children().toggle();
    })</script>
    Login or Signup to reply.
  2. You should use that code:

    $('.dropdown').on('mouseenter', function(e) {
      $(this).find('.dropdown-menu').addClass('open')
    }).on('mouseleave', function(e) {
      $(this).find('.dropdown-menu').removeClass('open')
    })
    
    $('.dropdown-menu li').on('click', function(e) {
      $(this).parent().removeClass('open')
    })
    

    And you should add that CSS

      .dropdown-menu.open {
        display: block;
      }
    

    And remove CSS related to the hover effect
    https://jsfiddle.net/jfagLrxp/23/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search