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" />
You can use event bubbling to do what you want, like this:
When a
clickbubbles todocument(normal bubble behavior), we hideul.left. When you click inside that<ul>, you can just prevent that bubble from happening usingevent.stopPropagation()…so clicking anywhere outside the<ul>causes it to hide, anywhere inside has no additional effects 🙂