简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM