This simple test code works in all browsers except IE (tested in IE8):
#dBox {
height:100px;
width: 230px;
overflow-y:auto;
}
$(function () {
$('#s').focus(function(){
$(this).after('<ul id="dBox"></ul>');
for (i=0;i<10;i++) $('#dBox').append('<li>'+i+'</li>');
});
$('#dBox').live('mousedown',function(event) {
//event.stopPropagation();
//event.preventDefault();
//console.log (event.isDefaultPrevented());
//event.stopImmediatePropagation();
return false;
});
$('#s').blur(function () { $('#dBox').remove(); });
});
<input type="text" id="s"/>
I've tried all the options from live fn., but no luck.
On event.isDefaultPrevented()
it returns true, but #dBox
it's still removed.
I've even tried to bind a regular mousedown inside the focus fn. But the same result it's working in all browsers but not IE.
Does anyone have any idea of what's wrong?
This is directly because of Event Delegation with jQuery live() binding events using live does not bind the direct element. Instead it attaches a handler on the root node of the document.
The .live() method is able to affect
elements that have not yet been added
to the DOM through the use of event
delegation: a handler bound to an
ancestor element is responsible for
events that are triggered on its
descendants. The handler passed to
.live() is never bound to an element;
instead, .live() binds a special
handler to the root of the DOM tree.
In our example, when the new element
is clicked, the following steps occur:
Assuming you want to keep focus on the input when the #dBox element is clicked this will work and here is a demo http://www.jsfiddle.net/WurDE/
Note: if you do not want to retain focus on the input then remove the trigger('focus')
from the code.
$(function () {
$('#s').focus(function(){
if (!$('#dBox').length) {
var $dbox = $('<ul id="dBox"></ul>');
for (i=0;i<10;i++) $dbox.append('<li>'+i+'</li>');
$(this).after($dbox);
$dbox.bind("mousedown", function() {
$('#s').unbind('blur')
});
$dbox.bind("mouseup", function() {
$('#s').bind('blur', function () {
$('#dBox').remove();
}).trigger('focus');
});
}
});
$('#s').bind('blur', function () {
$('#dBox').remove();
});
});