How can I fire the onclick event first before the onblur event if I'm currently focused at the textbox in jQuery?
Expected Output: Fire the button click event first before the blur event in the texbox. Alerts "mybtn onclick alert"
Demo: http://jsfiddle.net/Zk8Fg/
Code:
<input type="text" name="fname" id="fname" value="" /><br />
<input type="button" name="mybtn" id="mybtn" value="Click Me" />
<script language="javascript">
$(document).ready(function() {
myFunc();
});
function myFunc() {
$('#fname').focus().blur(function() {
alert('fname onblur alert');
});
$('#mybtn').click(function() {
alert('mybtn onclick alert');
});
}
</script>
Thanks :)
The divs inside the menu also have onclick() events which execute the special processing. The problem is that the onclick() events never fire when the menu is clicked, because the input field's onblur() fires first and deletes the menu, including the onclick() s!
The onblur event occurs when an object loses focus. The onblur event is most often used with form validation code (e.g. when the user leaves a form field).
$( "#field1" ). blur(function() { alert( "Lose focus from Field1" ); }); Note : In jQuery blur( handler ) method is used to bind an event handler to the "blur" JavaScript event, or trigger that event on an element.
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.
Well it's probably part of the standard which event fires first so you probably shouldn't be changing the order. What you could do though is postpone the resulting action using window.setTimeout
with a short delay.
$('#fname').focus().blur(function() {
window.setTimeout(function(){alert('fname onblur alert')},0.1);
});
I agree with the other comments though, it really looks like you should rethink how you're going about this because reordering default events strikes me as a lame hack that probably has more elegant solutions.
If the input field is presently focused, you cannot focus on another element without first blurring your present focus. Whatever it is you're attempting to do, there's probably a better way.
Visible Logging of Events: http://jsfiddle.net/Zk8Fg/3/
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