Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 236
mk_89 Avatar asked Mar 08 '12 22:03

mk_89


People also ask

How do you show a div for 10 seconds and then hide it?

Select the div element. Use delay function (setTimeOut(), delay()) to provide the delay to hide() the div element.

What does hide () do in jQuery?

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.


2 Answers

You should use stopPropagation:

$(body).click(function(e)
{
   $('#optionsMenu').slideUp('fast');
});
$('#optionsMenu').click(function(e)
{
   e.stopPropagation();
});
like image 93
Roberto Avatar answered Sep 28 '22 03:09

Roberto


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.

like image 30
David Thomas Avatar answered Sep 28 '22 03:09

David Thomas