7
votes

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 :)

2
What are you trying to do with $.focus().blur()?Sampson
Can I ask why and/or what you are trying to do? maybe someone will be able to suggest some alternatives? UI Events happen is certain order and I don't think it can be changed.Bala R
@Jonathan: I have a validation on the blur event currently focused at the textbox but the blur scenario is once I clicked the button then the blur event fires first than the click event.marknt15

2 Answers

6
votes

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.

3
votes

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/