After pressing enter I would like that only the keyup
event be fired but blur
is fired first. How to cancel blur
when keyup
is fired with enter?
Please don't suggest to bind both blur
and keyup
into a single live()
method.
$(".textbox").on("blur",function () {
alert("blur Event fired");
});
$(".textbox").on("keyup",function (event) {
if(event.keyCode == 13){ // Detect Enter
alert("KeyUp fired after pressing Enter");
}
});
Preventing the blur If you want to prevent the blur event from being fired, you have to do so when you are inside the mousedown event, you can do so by invoking the method preventDefault() on the event. Click the checkbox, focus input & then click the button, the textfield never loses focus now.
The keyup event is fired when a key is released. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup , but as 97 by keypress .
Definition and Usage The onkeyup event occurs when the user releases a key (on the keyboard). Tip: The order of events related to the onkeyup event: onkeydown. onkeypress. onkeyup.
In browsers, pressing the tab key when a control has focus will move it to the next element in the tab order, causing the current element to lose focus and dispatch a blur event. Therefore you can just test for the pressing of the tab key and call your function based on that, e.g.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With