How to blur the div element?
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?
Solution 1:
Try using tabindex attribute on your div, see:
Check this post for more information and demo.
Solution 2:
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>