How to blur the div element?

63,036

Solution 1

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.

<head>
  <script>
  $(document).ready(function(){
    $("body").click(function(e) {
      if(e.target.id !== 'menu'){
        $("#menu").hide();
      }      
    });
  });
  </script>
  <style>#menu { display: none; }</style>
</head>

<body>
  <div id="menu_button" onclick="$('#menu').show();">Menu....</div>
  <div id="menu"> <!-- Menu options here --> </div>

  <p>Other stuff</p>
</body>

Solution 2

Try using tabindex attribute on your div, see:

Check this post for more information and demo.

Solution 3

$("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.

Solution 4

Not the cleanest way, but instead of capturing every click event on the page you could add an empty link to your div and use it as a "focus proxy" for the div.

So your markup will change to:

<div><a id="focus_proxy" href="#"></a></div>

and your Javascript code should hook to the blur event on the link:

$('div > #focus_proxy').blur(function() { $('div').hide() })

Don't forget to set the focus on the link when you show the div:

$('div > #focus_proxy').focus()
Share:
63,036
Aamir Afridi
Author by

Aamir Afridi

Front-end/NodeJs developer based in London, UK

Updated on July 17, 2022

Comments

  • Aamir Afridi
    Aamir Afridi almost 2 years

    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?