Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How to fire onclick first before onblur?

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

like image 993
marknt15 Avatar asked Jun 23 '11 03:06

marknt15


People also ask

Does onBlur fires before Onclick?

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!

When onBlur event fires?

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

How to bind blur event in jQuery?

$( "#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.

How do you stop the blur event reaction?

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.


2 Answers

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.

like image 96
SpliFF Avatar answered Oct 25 '22 19:10

SpliFF


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/

like image 28
Sampson Avatar answered Oct 25 '22 20:10

Sampson