Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
892 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 Reply

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')
     });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...