Categories
JavaScript Answers

How to avoid Bootstrap dropdown menu close on click inside with JavaScript?

Spread the love

To avoid Bootstrap dropdown menu close on click inside with JavaScript, we stop the click event’s propagation.

For instance, we write

<ul class="nav navbar-nav">
  <li class="dropdown mega-dropdown">
    <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown">
      <i class="fa fa-list-alt"></i> Menu item 1
      <span class="fa fa-chevron-down pull-right"></span>
    </a>
    <ul class="dropdown-menu mega-dropdown-menu">
      <li>
        <div id="carousel" class="carousel slide" data-ride="carousel">
          <ol class="carousel-indicators">
            <li data-slide-to="0" data-target="#carousel"></li>
            <li class="active" data-slide-to="1" data-target="#carousel"></li>
          </ol>
          <div class="carousel-inner">
            <div class="item">
              <img alt="" class="img-rounded" src="img1.jpg" />
            </div>
            <div class="item active">
              <img alt="" class="img-rounded" src="img2.jpg" />
            </div>
          </div>
          <a
            data-slide="prev"
            role="button"
            href="#carousel"
            class="left carousel-control"
          >
            <span class="glyphicon glyphicon-chevron-left"></span>
          </a>
          <a
            data-slide="next"
            role="button"
            href="#carousel"
            class="right carousel-control"
          >
            <span class="glyphicon glyphicon-chevron-right"></span>
          </a>
        </div>
      </li>
    </ul>
  </li>
</ul>

to add the dropdown menu.

Then we write

$("ul.dropdown-menu.mega-dropdown-menu").on("click", (event) => {
  event.stopPropagation();
});

to select the drop down menu with jQuery $.

And we add a click handler to the element and then call stopPropagation to stop the click event’s propagation to stop the menu from showing when we click inside.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *