mk_89
mk_89

Reputation: 2742

hiding DIV when clicking away from it

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

Answers (2)

Roberto
Roberto

Reputation: 528

You should use stopPropagation:

$(body).click(function(e)
{
   $('#optionsMenu').slideUp('fast');
});
$('#optionsMenu').click(function(e)
{
   e.stopPropagation();
});

Upvotes: 10

David Thomas
David Thomas

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

Related Questions