jQuery button open list, list closed when clicked outside

I know there are a dozen of question on this on SO, but none of them seem to work for me. What I am trying is the following code:

jQuery('.mybutton').click(function(){

  jQuery('.list').show().bind('click', function(event){
    event.stopPropagation();
  });

  jQuery('html').bind('click', function() {
    jQuery('.list').hide();
  });
});

The list item never opens. The html bind click is always fired.

Answers


Instead of binding the click to the html and .list, bind it globally, and check whether the current target is (a child of) a .list element.

jQuery('.mybutton').click(function(){
  jQuery(window).click(function(event) {
       var $elem = $(event.target)
       if($elem.hasClass('list') || $elem.parents('.list').length == 0) return;
       jQuery('.list').hide();
   });
});

You shouldn't really be binding events on click like that. Try something like this instead.

jQuery('.mybutton').click(function(e){
  jQuery('.list').show();
   e.stopPropagation();
});

jQuery('body').click(function() {
  jQuery('.list').hide();
});

jQuery('.list').click(function(e){
  e.stopPropagation();
});

I think the main problem is that you need a stopPropagation call in your mybutton click handler too.


Need Your Help

jquery get radio value on change

javascript jquery html

i am using: http://blogs.digitss.com/javascript/jquery-javascript/jquery-fancy-custom-radio-and-checkbox/

Sccm 2007 collection query for particular service not instaled in services.msc

sccm system-center sccm-2007

Sccm collection query to get the list of machines which do not have "sms host agent" service installed.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.