tags:

views:

17

answers:

2

I recreated a Select box and its 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...

+2  A: 

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();
});
Nick Craver
A: 

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