Why does this code hide the div that’s used as the jQuery selector on blur() if I click inside it? Blur() should only hide it if I click outside it.
HTML trigger:
<div class="header">To-Do <a class="triggernewtodo">Add a task...</a></div>
li to show/hide:
<li class="addnewtodo">
<form>
<textarea class="addtodotextarea"></textarea>
<div class="controlarea">
<input class="primary" name="commit" type="submit" value="Add" />
</div>
</form>
</li>
jQuery:
// Show/Hide New Todo form
$('a.triggernewtodo').click(function() {
$('li.addnewtodo').show()
$('textarea.addtodotextarea').focus();
});
$('li.addnewtodo').live("blur", function() {
$(this).hide();
})
My guess is that it has something to do with the .focus() placed on the textarea, because if I take out that .focus(), it works properly until I click inside the textarea then click out (still inside the list item) and it hides the whole list item. Any ideas? What am I doing wrong?
I suspect you’re seeing an event that’s “bubbled up” from within that LI. Essentially, a “blur” event from the INPUT, say, triggers all the “blur” handlers on that input. Then it triggers all the “blur” handlers on the FORM. Then it triggers the “blur” handlers on the LI – hiding it.
The event continues all the way up the DOM tree unless you call stopPropagation to prevent this. In your case, you should be able to use the event.target property to see if the event actually originated at the LI, and only hide it in that situation (warning: untested):
Hope that helps!
PS: See the page on the blur event for additional caveats.