Nikita_Zhurb
Nikita_Zhurb

Reputation: 53

DropDown list issue

I have a table that has a dropdown button on each row. When you click on the button, a drop-down list opens, when you click outside the area, the drop-down list is closed. How to make sure that when clicked in the drop-down list area, it does not close? And how to make sure that when you click on another button with a drop-down list, the previous drop-down list is closed?

$(".dropdown").click(function(e) {
  $(this).find(".dropdown-menu").slideToggle();
});

$(document).on("click", function(event) {
  var $trigger = $(".dropdown");
  if ($trigger !== event.target && !$trigger.has(event.target).length) {
    $(".dropdown-menu").slideUp("fast");
  }
});
.dropdown {
  display: inline-block;
  position: relative;
}

.dropdown-menu {
  text-align: center;
  font-size: 14px;
  background-color: #ffffff;
  color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td>
  <li class="dropdown">
    <button></button>
    <ul class="dropdown-menu">
      <li></li>
      <li></li>
    </ul>
  </li>
</td>

Upvotes: 3

Views: 145

Answers (1)

Karan
Karan

Reputation: 12629

Update your $(".dropdown").click(function(e) { ... } as below.

  1. Use slideDown instead of slideToggle to set it always open.
  2. select all dropdown-menu and remove current dropdown-menu with $(".dropdown-menu").not($(this).find(".dropdown-menu")) and apply .slideUp("fast").

Try it below.

$(".dropdown").click(function(e) {
  // use slideDown instead of slideToggle to set it always open.
  $(this).find(".dropdown-menu").slideDown();
  // select all dropdown-menu and remove current dropdown-menu with .not
  // hide other dropdowns.
  $(".dropdown-menu").not($(this).find(".dropdown-menu")).slideUp("fast");
});

$(document).on("click", function(event) {
  var $trigger = $(".dropdown");
  if ($trigger !== event.target && !$trigger.has(event.target).length) {
    $(".dropdown-menu").slideUp("fast");
  }
});

$(".dropdown-menu").slideUp();
.dropdown {
  display: inline-block;
  position: relative;
}

.dropdown-menu {
  text-align: center;
  font-size: 14px;
  background-color: #ffffff;
  color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
  <tr>
    <td>1</td>
    <td>
      <li class="dropdown">
        <button>open dropdown</button>
        <ul class="dropdown-menu" style="display: none;">
          <li>11</li>
          <li>12</li>
        </ul>
      </li>
    </td>
  </tr>
  <tr>
    <td>2</td>
    <td>
      <li class="dropdown">
        <button>open dropdown</button>
        <ul class="dropdown-menu" style="display: none;">
          <li>21</li>
          <li>22</li>
        </ul>
      </li>
    </td>
  </tr>
</table>

Upvotes: 1

Related Questions