teamsiems
teamsiems

Reputation: 13

Clearing toggle state

I have a form select replacement that uses jQuery to show options in a UL list when a user clicks a link. Clicking on an option changes a hidden form value and hides the list. Everything works fine, but if the user clicks somewhere outside the list or image I would like for the list to hide. It looks like I need to clear the toggle state and hide the list, but I haven't been able to do that. (Inspired by delicious.com multi-option search.)

$('ul.left').hide();

$('ul.downarrow li a').click(function(){
  $('ul.left').toggle();
});

$('ul.left li a').click(function() { 
  $('ul.left').hide();
  $('#sitesearchquery').val($(this).attr('name'));        
});

<ul class="downarrow">
  <li><a style="cursor:pointer; display:inline-block; width:20px; height:20px; background: url(images/down_arrow.gif);"></a>
    <ul class="left">
      <li><a href="#" name="mysite">My Site</a></li>
      <li><a href="#" name="othersite">Other Site</a></li>
    </ul>
  </li>
</ul>
...
<input type="hidden" name="sitesearch" id="sitesearchquery" value="mysite" />

Upvotes: 1

Views: 397

Answers (2)

Mark
Mark

Reputation: 33571

A plugin designed for your usecase:

http://benalman.com/projects/jquery-outside-events-plugin/

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630449

You can use event bubbling to do what you want, like this:

$('ul.downarrow').click(function(e){
  e.stopPropagation(); //stop event from bubbling
});
$(document).click(function() {
  $('ul.left').hide();
});

When a click bubbles to document (normal bubble behavior), we hide ul.left. When you click inside that <ul>, you can just prevent that bubble from happening using event.stopPropagation()...so clicking anywhere outside the <ul> causes it to hide, anywhere inside has no additional effects :)

Upvotes: 1

Related Questions