views:

2819

answers:

4

I have a dropdown menu inside a DIV.

I want the dropdown to be hide when user click anywhere else.

$('div').blur(function() { $(this).hide(); }

is not working.

I know .blur works only with <a> but in this case what is the simplest solution?

A: 

Change its opacity from 100 % to 0 and then hide it with display

Do

$('div').css({ "opacity": "0", "display": "none" });

or

Do

$('div').css({ 'opacity': '0', 'display': 'none' });

Its untested, but could work.. not sure if handling opacity this way works :)

Zayatzz
A: 

.click will work just fine inside the div tag. Just make sure you're not over top of the select element.

$('div').click(function(e) {
    var $target = $(e.target);
    if (!$target.is("select")) { $(this).hide() };
});
ScottE
How is a div ever going to be a select?
redsquare
Yep, should have tested, need to look at the target...
ScottE
+2  A: 

I think the issue is that divs don't fire the onfocusout event.

You'll need to capture click events on the body and then work out if the target was then menu div. If it wasn't, then the user has clicked elsewhere and the div needs to be hidden.

  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd"&gt;
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"&gt;&lt;/script&gt;

  <script>
  $(document).ready(function(){

    $("body").click(function (evt) {
         var target = evt.target;
      if(target.tagName !== 'DIV'){
      $(".menu").hide();
     }   
    });

  });
  </script>
  <style>span {display:none;}</style>
</head>
<body>
  <p><div class="menu">Menu....</div></p>

  Other Stuff


</body>
</html>
djch
I don't think this answers the question. My understanding is that aamir wants to hide the div when you click inside, unless you click the select element.
ScottE
This is wrong. What happens when the user clicks on another div which is not part of the menu?
rahul
A div can accept focus and issue onfocus and onblur if you specify a tabindex for it. Try this:`<div tabindex="100" onfocus="alert('!')"> Blah</div>`
vit
"This is wrong. What happens when the user clicks on another div which is not part of the menu?"Yes, thats true, it was just a simple example to demonstrate capturing events on the body and determining the actual element that was clicked. When properly implemented, you'd want to check other properties of the target (most likely the id) to ensure you were not clicking on the menu again.
djch
+1  A: 
$("body").click(function (evt) {
     var target = evt.target;
     if(target.id !== 'menuContainer'){
            $(".menu").hide();
    }                
});

give the div an id, for instance "menuContainer". then you can check by target.id instead of target.tagName to make sure its that specific div.

PulledBull