How to create a click event that is only called when clicking off of a div?

8

I need to click on a div (it's a register), it will close.

What selector should I use so that by clicking anywhere outside the div this div closes?

$(????).on("click", function(){
    $('div').hide();  
});

If you click on any part or element of div you will not be able to close because the user will be filling in the data.

    
asked by anonymous 07.03.2014 / 22:17

3 answers

10

You can associate the event with a more external element, for example body , and within the event check what the event's target is.

If the target is the DIV you want to exclude from the click event, then using a if do nothing in this case.

javascript

$(function() {
    var div = $("#div"); // seleciona a div específica
    $("body").on("click", function (e) {
        if (div.has(e.target).length || e.target == div[0])
            return;

        alert("Você clicou fora da div!");
    });
})

jsfiddle - deleting 1 event element

Deleting multiple areas of the event

Using closest as indicated by @mgibsonbr makes it even easier to extend the concept: for example, when you want exclude multiple areas of the event:

jsfiddle - deleting multiple event elements

    
07.03.2014 / 22:22
2

You can add the event click to document by firing for the entire page.

In%% of% within%% check that the target of the clicked location, if the ID is the same as that of the div, give if , otherwise run click .

It has a catch, needs to be checked if the return false element is the child of the element element should have the event clicked.

$(document).on("click", function (e) {
    var obj = 'item', id = $(e.target).attr('id');
    if (id==obj) return;
    if ($("#"+obj+" #"+id).length > 0) return;
    $("#"+obj).hide();
});

Look at the example in jsfiddle

    
07.03.2014 / 22:46
0

When we need to do something over and over again, it may be worth creating an extension in jQuery to solve this problem.

I did this:

(function ( $ ) {

    $.fn.clickOut = function (callback) {

        var that = this;

        $(document).click(function (e) {

            if ( $(e.target).closest(that).size() > 0) {

                return;
            }

            $.isFunction(callback) && $.proxy(callback, that)(e);
        });
    }

})( jQuery )

Then when I want a certain element to be closed only when it is clicked off, I do it as follows:

$('.fecha_quando_clica_fora').clickOut(function()
{
    $(this).hide()
});

See this on JSFIDDLE

    
15.10.2015 / 14:59