Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
908 views
in Technique[技术] by (71.8m points)

javascript - Close sidebar on click outside

I'm working a site using this Bootstrap example, with a simple slide in sidebar navigation.

http://ironsummitmedia.github.io/startbootstrap-simple-sidebar/#

It is slightly modified, so I have a button for the menu to open:

// Opens the sidebar menu
 $("#menu-toggle").click(function (e) {
    e.preventDefault();
       $("#sidebar-wrapper").toggleClass("active");
 });

And a button for the menu to close:

// Closes the sidebar menu
   $("#menu-close").click(function (e) {
       e.preventDefault();
       $("#sidebar-wrapper").toggleClass("active");
   });    

I want to add functionality, so it will close if I click anywhere outside the sidebar. So far I have this:

// Close the menu on click outside of the container  
$(document).click(function (e) {

            var container = $("#sidebar-wrapper");

            if (!container.is(e.target) // if the target of the click isn't the container...
                && container.has(e.target).length === 0 // ... nor a descendant of the container
                && event.target.id !== "menu-toggle")  // for the functionality of main toggle button
            {
                container.removeClass("active");
            }
     });

But it seems to remove the "active" class this way.

Best regards.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

So the solution should be that if you click anywhere inside the container the click handler should do nothing and just return. But if the click is outside the container then it should close it.

Below is the click handler code which might help you.

 $(document).click(function(e) {
      var node = e.target;
       // loop through ancestor nodes to check if the click is inside container.
       // If yes then return from the handler method without doing anything 
       while(node.parentNode) {
         if (node === container) {
           return;
         }
         node = node.parentNode;
       }

       container.removeClass('active')
     });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...