Fire onblur event before onchange event

I have a large form containing several text input fields. Essentially, I need to handle the onchange event for all fields and the onblur events for some fields. When a field changes and the field loses focus, both events fire (which is the correct behavior). The only problem is that I would like to handle onblur before handling the onblur event.

After some testing in ie and Firefox, it seems that the default behavior is to fire the onchange event before onblur . I used the following code as a test ...

 <html> <body > <input type="text" value="here is a text field" onchange="console.log('Change Event!')" onblur="console.log('Blur Event!')" > </body> </html> 

Which brings me to my questions:

  • This behavior seems to be consistent across browsers. Why onchange work onchange ?

  • Since I cannot handle the onblur event for each input element, is there a way I can trigger onblur before handling the onchange event?

+4
source share
2 answers
  • First, an onchange error onchange : when an element loses focus (that is, it “blurs”), the change usually ends (usually I say because the script can change the element without user interaction).

  • For those elements that first require onblur , you can turn off the onchange handler and run onchange (or even a custom event) from the onblur handler. This will ensure the correct order, even if it works more. To detect a change, you can use the state variable for this field.

As a general remark, however, the need for such synchronization is a sign that the approach you use to solve any problem you solve may require more work, although sometimes it cannot be avoided. If you are sure that this is the only way, try one of these methods!

EDIT: To elaborate on the last point, you will need to follow some assumptions about your event model. Do you assume that every change event is followed by blur and it is not processed otherwise or every change processed, and those followed by blur get further processing after onblur with them? In any case, if you want to ensure the execution of the order, the processors need access to the shared resource (global variable, property, etc.). Are there other types of events that you might want to use? ( input ?). Finally, this link contains some information about the change event for Mozilla browsers: https://developer.mozilla.org/en-US/docs/Web/Reference/Events/change . The third "bullet" solves the problem of the order of events.

+6
source

This is a bit of a hack, but it seems to be a trick in most browsers:

 <input type="text" value="Text Input" onchange="setTimeout(function(){console.log('Change Event!')}, 0);" onblur="console.log('Blur Event!');" /> 

Here you can see the fiddle: http://jsfiddle.net/XpPhE/

Below is a little help on the setTimeout(function, 0) trick: http://javascript.info/tutorial/events-and-timing-depth

Hope that helps :)

+3
source

Source: https://habr.com/ru/post/1496864/


All Articles