开发者

Jquery - check for clicks outside of a Select box

I recreated a Select box and its 开发者_JAVA百科dropdown function using this:

$(".selectBox").click(function(e) {
    if (!$("#dropDown").css("display") || $("#dropDown").css("display") == "none")
        $("#dropDown").slideDown();
    else
        $("#dropDown").slideUp();
    e.preventDefault();
});

The only problem is that if you click away from the box, the dropdown stays. I'd like it to mimic a regular dropdown and close when you click away, so I thought I could do a 'body' click:

$('body').click(function(){
    if ($("#dropdown").css("display") || $("#dropdown").css("display") != "none")
        $("#dropdown").slideUp();
});

But now, when you click the Select box, the dropdown slides down and right back up. Any ideas what I'm doing wrong? Thanks very much in advance...


You also need to stop a click from inside the #dropdown from bubbling back up to body, like this:

$(".selectBox, #dropdown").click(function(e) {
   e.stopPropagation();
});

We're using event.stopPropagation() it stops the click from bubbling up, causing the .slideUp(). Also your other 2 event handlers can be simplified with :visible or .slideToggle(), like this overall:

$(".selectBox").click(function(e) {
  $("#dropDown").slideToggle();
  return false;                  //also prevents bubbling
});
$("#dropdown").click(function(e) {
   e.stopPropagation();
});
$(document).click(function(){
  $("#dropdown:visible").slideUp();
});


Since you are setting an event handler that catches every click, you don't need another one on a child.

$(document).click(function(e) {
    if ($(e.target).closest('.selectBox').length) {
        $('#dropdown').slideToggle();
        return false;
    } else {
        $('#dropdown:visible').slideUp();
    }
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜