开发者

Close on click anywhere

I have the following script which works almost perfectly:

http://jsfiddle.net/oshirowanen/uUAqe/

I just need it to have 1 added ability where any dropdown will automatically close no matter wher开发者_如何学Pythone on the page the user clicks, be it on a blank part of the page, on a button, in a textbox etc etc.


Please see an updated jsFiddle page here: http://jsfiddle.net/KYqyU/

To explain what is done, firstly, you bind an click event to the document that will hide the navigation drop-downs.

$(document).click(function() {
    $('.dropdown').hide();
    $('.navigation').removeClass("active");
});

Then after that, you modify the click event on the .navigation class to return false which stops the document event from propagating and hiding the navigation in this instance.

$('.navigation').click(function() {
    $(this).siblings('.navigation.active').click();
    $(this).toggleClass('active').next().toggle();
    return false;
});

As Mark also points out, you can use event.StopPropagation() to stop the propagation. If you use this method you will need to pass event into the click callback function as an argument/parameter.


Try this out to hide the navigation...

$('.navigation').click(function(event) {
    $(this).siblings('.navigation.active').click();
    $(this).toggleClass('active').next().toggle();
    event.stopPropagation();
});
$(document).click(function(event) {
    $('.navigation.active').click();
    $('.navigation').removeClass("active");
});

This uses event.StopPropagation() which stops any events from bubbling up the dom. Since we only what to trigger the hide when .navigation is not the element clicked.

Example on jsfiddle.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜