Reputation: 4132
I have a text input, and a hidden list. The list will show and hide upon focusing and blurring the input. However, I want the list remain showing when I click on the list (outside the input), i.e., only hide the list when click on outside of it. How to achieve that?
==== html ====
<input type="text" id="regioninput">
<ol class="continentlist">
//php code to generate list items
</ol>
==== js ====
$('#regioninput').bind('focus', function() {
$('.continentlist').show();
});
$('#regioninput').bind('blur', function() {
$('.continentlist').hide();
});
$('.continentlist li').live('click', function() {
alert($(this).html());
...
});
Upvotes: 2
Views: 3106
Reputation: 76003
You can change your code a bit so instead of using blur
and focus
you can just use click
on different elements:
//show the list when you click the input
$('#regioninput').bind('click', function(event) {
event.stopPropagation();
$('.continentlist').show();
});
//hide the list when the document receives a click
$(document).bind('click', function () {
$('.continentlist').hide();
});
//make sure that if the user clicks on the list they won't hide it
$('.continentlist').bind('click', function(event) {
event.stopPropagation();
});
Here is a demo: http://jsfiddle.net/qUeXS/
event.stopPropagation()
stops the event from bubbling up the DOM: http://api.jquery.com/event.stoppropagation
On a side-note, this works because of event bubbling. No matter where you click on a document, the document
object will receive that click event after it bubbles all the way up the DOM. So if we cancel the bubbling of the event we can stop the document
object from receiving the event.
Upvotes: 4