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.
Select the div element. Use delay function (setTimeOut(), delay()) to provide the delay to hide() the div element.
jQuery hide() Method The hide() method hides the selected elements. Tip: This is similar to the CSS property display:none. Note: Hidden elements will not be displayed at all (no longer affects the layout of the page). Tip: To show hidden elements, look at the show() method.
You should use stopPropagation:
$(body).click(function(e)
{
$('#optionsMenu').slideUp('fast');
});
$('#optionsMenu').click(function(e)
{
e.stopPropagation();
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With