Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap dropdown not closing on clicking outside

In my application I have added close button side bootstrap dropdown. Clicking on that close button I have to close that dropdown. This is working properly, but when I click anywhere outside dropdown, dropdown is not closing Here is Fiddle : goo.gl/3RAkBw

Can any one tell me how can I close

like image 599
vaibhav shah Avatar asked Oct 18 '22 00:10

vaibhav shah


2 Answers

You can try this:

$(document).on('click',function(){
    $('#layers').hide();
  })
like image 69
Franco Avatar answered Oct 21 '22 01:10

Franco


   $( document.body ).on( 'click', '.dropdown-menu li', function( event ) {

      var $target = $( event.currentTarget );

      $target.closest( '.btn-group' )
         .find( '[data-bind="label"]' ).text( $target.text() )
            .end()
         .children( '.dropdown-toggle' ).dropdown( 'toggle' );

      return false;

   });
   $(window).on('click', function () {
     $( '#layers' ).css( 'display','none' );
   });
.btn-input {
   display: block;
}

.btn-input .btn.form-control {
    text-align: left;
}

.btn-input .btn.form-control span:first-child {
   left: 10px;
   overflow: hidden;
   position: absolute;
   right: 25px;
}

.btn-input .btn.form-control .caret {
   margin-top: -1px;
   position: absolute;
   right: 10px;
   top: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet"/>
<br/><br/>



         <div class="panel panel-default">
            <div class="panel-body">
               <div class="btn-group">
                 <button onclick="$('#layers').toggle();" type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                   <span data-bind="label">Select One</span>&nbsp;<span class="caret"></span>
                 </button>
                 <ul id="layers" class="dropdown-menu" role="menu">
                 <span><img class="close_img dropdown-toggle" onclick="$('#layers').toggle();" data-toggle="dropdown" src="https://www.eonenergy.com/images/icons/close.gif" alt="CloseWindow" title="Close" style="margin-top:5px;margin-right:5px" /></span>
                   <li><a href="#">Item 1</a></li>
                   <li><a href="#">Another item</a></li>
                   <li><a href="#">This is a longer item that will not fit properly</a></li>
                 </ul>
               </div>
             </div>
          </div>

 
<br/><br/>

You can set click event on window like, (if you have to hide only on click of anywhere on window)

$(window).on('click', function () {
     $( '#layers' ).css( 'display','none' ); //$( '#layers' ).hide();
   });
like image 34
Dhara Avatar answered Oct 20 '22 23:10

Dhara