开发者

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

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, the div fades out, but i can click on the select and type in the search input and not have i开发者_如何学编程t fade? any help is appreciated. -nick


Code Duck's answer is incomplete, because you'd need to have it not fade out if you click the DIV itself (only outside). So say your DIV that's supposed to fade out has an ID of "menu".

jQuery("#menu").click(function(){ return false; });
jQuery(document).one("click", function() { jQuery("#menu").fadeOut(); });

The use of one is more concise than the bind/unbind. Also namespaced events aren't really needed here if you use one because there's no need to explicitly unbind a particular click handler on document.

The return false is just saying "stop bubbling this event up to the document."


Many modal dialogs use an partially transparent overlay that covers the entire page indicating that the dialog has focus. I would consider this the best way to accomplish what you want. If you really don't want the page darkened or grayed out, you can always just make the overlay completely transparent. For an example check out Facebox.


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


$("#menu").click(function(){
        $(document).unbind("click");
        $("#menu").show();
        $("#menu").bind('mouseout',function(){
        $(document).bind("click",function(){$("#menu").fadeOut();});
        });
});

This should do.. cheers.


Check this out
Demo is here

$('#menuBtn').click(function(e) {
    e.stopPropagation();
    $('.navMenuSecWrapper').fadeToggle();
    return false;
});

$(document).click(function() {
    $('.navMenuSecWrapper').fadeOut();
});


You can bind a click handler on $(document) like

$(document).click(function(){
  $(this).unbind('click');
  $('#menu').fadeOut();
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜