Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collapse bootstrap button on click outside

I am using this code, which is taken almost out of the box from the bootstrap docs, to get a simple collapse behaviour for a button (I converted the button to a link):

<button class="btn btn-link" type="button" data-toggle="collapse"     data-target="#collapseTree" aria-expanded="false"         aria-controls="collapseTree">
     <b>click me</b>
             </button>
                 <div class="collapse" id="collapseTree">
                       <div class="well">
                           <h6>Example text goes here</h6>
                       </div>
                 </div>

Now, what I am trying to do is to be able to close the text when the user clicks outside the button. I know that is asked many times in stack overflow but jQuery is NOT AT ALL intuitive ! at least for a beginner like me, so I am not really able to adapt any of the solutions proposed on this SO answer to get the desired behaviour.

For example, I am using this script (concept borrowed from here to try to control the outside click behaviour of the above code :

<script>
  $(document).ready(function () {
      $(document).click(function (event) {
      var clickover = $(event.target);
      var _opened = $(".btn-link").hasClass("collapse");
             if (_opened === true && !clickover.hasClass("data-toggle") && clickover.parents('.btn-link').length == 0) {
                $("button.data-toggle").click();
             }
       });
  });
</script>

but of course with no luck. Any hint would be greatly appreciated !

UPDATE

Another try with no luck here.

like image 888
pebox11 Avatar asked Jan 21 '26 08:01

pebox11


1 Answers

you could use the following:

//handling the hiding when clicking anywhere else in the document
$(document).mouseup(function(e)
{
    var container = $('.btn-link');
    if (container.has(e.target).length === 0) {
      // the closing function
    }
});
like image 105
AhmadAssaf Avatar answered Jan 23 '26 21:01

AhmadAssaf