Hiding the div when you click on it

Im basically trying to create a simple drop down menu with html, css and jquery and they are having trouble closing the div when the user clicks on it.

I tried stopPropagation and attached the action to the document when clicked, they either do not work, or I do not know how to use them. anyway 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 very helpful.

+7
source share
2 answers

You should use stopPropagation:

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

You can use on() , perhaps:

 $('body').on('click', function(e){ if ($(e.target).not('#optionsMenu')){ $('#optionsMenu').slideUp('fast'); } }); 

The above has not been verified, but should, I think, work.

+3
source

All Articles