开发者

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 Sit开发者_开发百科e</a></li>
    </ul>
  </li>
</ul>
...
<input type="hidden" name="sitesearch" id="sitesearchquery" value="mysite" />


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 :)


A plugin designed for your usecase:

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜