Jquery, how: click anywhere outside of the div, the div fades out

前端 未结 6 1420
甜味超标
甜味超标 2020-12-09 06:37

In Jquery how would i make it so that if i had a div, with different elements inside of it, a select, a search input, etc, that when i click outside of the div, on the page,

6条回答
  •  失恋的感觉
    2020-12-09 06:58

    I know this is an older question, but here's an extension I wrote to add a clickOutside function to elements:

    $.fn.extend({
    // Calls the handler function if the user has clicked outside the object (and not on any of the exceptions)
    clickOutside: function(handler, exceptions) {
        var $this = this;
    
        $("body").bind("click", function(event) {
            if (exceptions && $.inArray(event.target, exceptions) > -1) {
                return;
            } else if ($.contains($this[0], event.target)) {
                return;
            } else {
                handler(event, $this);
            }
        });
    
        return this;
    }
    

    }

    With this you could easily do

    $("#menu").clickOutside(function(event, obj) { obj.fadeOut() });
    

提交回复
热议问题