Reputation: 2742
Im basically trying to make a simple dropdown menu with html, css and jquery and im having trouble with closing the div when a user clicks away from it.
i've tried stopPropagation and binding an action to the document when clicked, they either do not work or I have no idea how to use them. anyway have a look at the code below
HTML
<div id="optionsMenu">
<a href="account.php?edit=info">Account Settings</a>
</div>
JQuery
$('.options').click(function(){
if($('#optionsMenu').css("display") == 'none'){
$('#optionsMenu').slideDown("fast");
}
else{
$('#optionsMenu').slideUp("fast");
}
});
$('#optionsMenu').blur(function(){
$('#optionsMenu').css("display","none");
});
any help would be much appriciated.
Upvotes: 7
Views: 5958
Reputation: 528
You should use stopPropagation:
$(body).click(function(e)
{
$('#optionsMenu').slideUp('fast');
});
$('#optionsMenu').click(function(e)
{
e.stopPropagation();
});
Upvotes: 10
Reputation: 253506
You could use on()
, perhaps:
$('body').on('click', function(e){
if ($(e.target).not('#optionsMenu')){
$('#optionsMenu').slideUp('fast');
}
});
The above not yet tested, but should, I think work.
Upvotes: 3