[javascript] Close a div by clicking outside

I want to hide a div by clicking on the close link in it, or by clicking anywhere outside that div.

I am trying following code, it opens and close the div by clicking close link properly, but if I have problem to close it by clicking anywhere outside the div.

_x000D_
_x000D_
$(".link").click(function() {_x000D_
  $(".popup").fadeIn(300);_x000D_
}_x000D_
_x000D_
);_x000D_
$('.close').click(function() {_x000D_
  $(".popup").fadeOut(300);_x000D_
}_x000D_
_x000D_
);_x000D_
$('body').click(function() {_x000D_
  if (!$(this.target).is('.popup')) {_x000D_
    $(".popup").hide();_x000D_
  }_x000D_
}_x000D_
_x000D_
);
_x000D_
<div class="box">_x000D_
  <a href="#" class="link">Open</a>_x000D_
  <div class="popup">_x000D_
    Hello world_x000D_
    <a class="close" href="#">Close</a>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Demo: http://jsfiddle.net/LxauG/

This question is related to javascript jquery html

The answer is


Add a transparent background taking up the whole window size, just before your popup div

.transparent-back{
    position: fixed;
    top: 0px;
    left:0px;
    width: 100%;
    height: 100%;
    background-color: rgba(255,255,255,0.5);
}

Then on its click, dismiss the popup.

$(".transparent-back").on('click',function(){
    $('popup').fadeOut(300);
});

You need

$('body').click(function(e) {
    if (!$(e.target).closest('.popup').length){
        $(".popup").hide();
    }
});

I'd suggest using the stopPropagation() method as shown in the modified fiddle:

Fiddle

$('body').click(function() {
    $(".popup").hide();
});

$('.popup').click(function(e) {
    e.stopPropagation();
});

That way you can hide the popup when you click on the body, without having to add an extra if, and when you click on the popup, the event doesn't bubble up to the body by going through the popup.


You'd better go with something like this. Just give an id to the div which you want to hide and make a function like this. call this function by adding onclick event on body.

function myFunction(event) { 

if(event.target.id!="target_id")
{ 
    document.getElementById("target_id").style.display="none";
  }
}

This question might have been answered here. There might be some potential issues when event propagation is interrupted, as explained by Philip Walton in this post.

A better approach/solution would be to create a custom jQuery event, e.g. clickoutside. Ben Alman has a great post (here) that explains how to implement one (and also explains how special events work), and he's got a nice implementation of it (here).

More reading on jQuery events API and jQuery special events:


 //for closeing the popover when user click outside it will close all popover 
 var hidePopover = function(element) {
        var elementScope = angular.element($(element).siblings('.popover')).scope().$parent;
        elementScope.isOpen = false;
        elementScope.$apply();
        //Remove the popover element from the DOM
        $(element).siblings('.popover').remove();
    };
 $(document).ready(function(){
 $('body').on('click', function (e) {
       $("a").each(function () {
                    //Only do this for all popovers other than the current one that cause this event
           if (!($(this).is(e.target) || $(this).has(e.target).length > 0) 
                && $(this).siblings('.popover').length !== 0 && $(this).siblings('.popover').has(e.target).length === 0)                  
                    {
                         hidePopover(this);
                    }
        });
    });
 });

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment