title: Expand on click, collapse on click outside
body: <p>I have an element which I want to expand on click and then collapse on click outside and thus came up with the following code. However when I run this it will start to expand and then immediately collapse since both functions are called sequentially. I don't understand why and how to solve this.</p>
  
  <pre><code>jQuery(document).ready(function() {
  
  var element         = jQuery("#search-main");
  var defaultWidth    = jQuery("#search-main").css('width');
  var expandWidth     = "200px";
  
  var fnSearch = {
      expand : function() {
  
          jQuery(element).animate({
              width : expandWidth
          });
  
          jQuery(document).bind('click', fnSearch.collapse);
      },
  
      collapse : function() {
  
          jQuery(element).animate({
              width : defaultWidth
          });
  
          event.stopPropagation();
  
          jQuery(document).unbind("click", fnSearch.collapse);
  
      }
  }
  
  jQuery("#search-main").bind("click", fnSearch.expand);
  
  });
  </code></pre>