JQuery: How to start onclick first before onblur?

How can I fire an onclick event earlier than an onblur event if I am currently focused on a text field in jQuery?

Expected Result: Fire the button press event first before the texbox blur event. Mybtn onclick alert alerts

Demo: http://jsfiddle.net/Zk8Fg/

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

+7
source share
2 answers

Well, this is probably part of the standard whose event fires first, so you probably shouldn't change the order. What you could do is postpone the action with window.setTimeout with a slight delay.

 $('#fname').focus().blur(function() { window.setTimeout(function(){alert('fname onblur alert')},0.1); }); 

I agree with the other comments, although it seems you should rethink how you are going to do this because reordering events by default amazes me like a lame hack that probably has more elegant solutions.

+6
source

If the input field is currently focused, you cannot focus on another element without first blurring your current focus. Whatever you are trying to do is probably the best way.

Visible event log: http://jsfiddle.net/Zk8Fg/3/

+3
source

All Articles