Edit
To prevent both events from firing, you'll have to somehow mark the element before causing it to lose focus. That way, your blur
event handler can tell if the event is the subject of a keyup, or if it legitimately lost focus. Something like this:
$(".textbox").live("blur",function (event) {
if (!$(this).hasClass('keyupping'))
alert("blur Event fired");
});
$(".textbox").live("keyup",function (event) {
$(this).addClass('keyupping');
if(event.keyCode == 13){ // Detect Enter
alert("KeyUp fired after pressing Enter");
}
$(this).removeClass('keyupping');
});
Try it out: http://jsfiddle.net/GRMule/sR6zm/
Original answer
When the event for keyup
fires, it prepares to draw the browser alert dialog, which takes focus from the document and applies it to the modal dialog. This causes the blur event to fire.
The blur
event is then jumping in and finishing its execution context before keyup
knows what hit it.
This is demonstrated by using something that does not take the focus off the element, like console.log
: http://jsfiddle.net/GRMule/7vRLW/
The order that events fire is implementation-specific, meaning that you can't rely on Firefox acting like IE. See the spec: http://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/events.html#Events-eventgroupings. Try the fiddle with alerts in IE, and in this case you'll see that blur
does hit before keyup
in IE 7 -- and blur
doesn't fire in Chrome!