About

Labels

slider

Recent

Navigation

Click out of the container to close it using jQuery


This is a questions once asked by my class mate while studying the boring Physics class. We were sitting at the last bench while teacher were busy with Newton's Ring Experiment, we were discussing how to handle a popup menu. Finally I came out with two solutions.

Method #1

This solution is easy to use and good for popups. Actually this one works with a simple methodology of layer before popup. This layer will cover the whole screen. Once the user will click the layer behind the popup, the layer and popup will fade out.

How it works?

Take a website with a button that triggers popup menu.
<div class='popup'>This is the popup</div>
<div class='overlay'></div>
<div class='content'>This is the main content ....<span class='clickme'>Click Me</span></div>
Then CSS would be:
.popup{
display:none;
position:fixed;
top:20px;
z-index:3;
}
.overlay{
display:none;
position:fixed;
width:100%;
height:100%;
left:0;
top:0;
background:rgba(0,0,0,0.6);
z-index:2;
}

So now we have a layout, once the button is clicked the popup and layer both will appear:
$('.clickme').click(function(){
    $('.overlay,.popup').fadeIn();
});


Now behind popup a semi transparent layer is the closing agent for popup. If you just add an event on that layer to close the popup then user can easily close the popup by clicking on that layer. Works good specially in small screen sizes where do not have to find small close buttons to close popups.
See the Pen Popup Hadnling by Mohammad Hamza Dhamiya (@hamzadhamiya) on CodePen.
Well this method I thing have a limitation that it could work on those elements only that covers the whole screen, but what about those who have a small space in the DOM. For them try method #2.

Method #2

Second method is also quite easy and works well with every condition. This one works with the current position mouse. Have a look at demo first:
See the Pen XJOwWo by Mohammad Hamza Dhamiya (@hamzadhamiya) on CodePen.
Now this one works with the mouseup function of jQuery that gives the current mouse pointer position. On every mouse move we have to make sure that neither the clicked element is the container nor its child.
$(document).mouseup(function(e){
    var foo=$('.notification');
     if (!foo.is(e.target) // Check if this is the container
        && foo.has(e.target).length === 0) // ... nor its child
    {
   $('.notification').removeClass('active');
    }
  });
Now this what I was taking about. This one works with every kind of situations. 
Share
Banner

Muhammad Hamza

Themelet provides the best in market today. We work hard to make the clean, modern and SEO friendly blogger templates.

Post A Comment:

0 comments: