简体   繁体   中英

Toggle close outside click

I am using toggle class for dd & dt it is working fine but my problem is if user click out side i want to close that toggle. How to achive this ?

 <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.js"></script>
    <script type="text/javascript">
    jQuery=$.noConflict();
    jQuery(document).ready(function() {
        jQuery('.navigation dd').hide(); 

        jQuery('.navigation dt').click(function(){ 
                jQuery(this).next('dd').slideToggle('slow');
                jQuery(this).toggleClass('glace_navigationlayer-collapsed'); 


            });


     }); 
    </script>

You can also try -- what DBS has is proper , ( he posted in a comment ), imho.

//clicking on the body, closes the toggleitem
jQuery(document.body).bind('click.closedd', function() {
    jQuery('.navigation dd').hide();
});

// clicking on the toggle item, won't trigger the click on the body
// that we set up above.
jQuery('.navigation dd').bind('click.closedd', function(e) {
    e.stopPropagation();
});

You need to listen for clicks on the <body> and then check to make sure the target is outside of the navigation component.

jQuery('body').on('click', function(evt) {
  var $target = $(evt.target);
  if ( !$target.closest('.navigation').length ) {
    // code to collpase the nav menu
  }
});

I would also recommend refactoring your nav code to use separate expand and collapse functions instead of relying on slideToggle and toggleClass .

Good luck!

Not too sure about the requirements, but you can try achieving the above on mouseenter and mouseleave events.
However, if you have to implement the above functionality only on click, then you will have to wire the click event on a container that covers the entire html body.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM