简体   繁体   中英

Javascript: Reset the selected focus on an element that is being rerendered

I'm using dust.js in order to render Javascript templates to HTML. Using dust.js, I've basically broken my page into template components, that are rerendered in response to certain events. One such component/template conceptually looks as follow:

[Label] [Input1] [Input2] [Input3]

All 3 inputs in this component have an onBlur event which is used to recalculate the value of the other inputs and which in turn causes the template to rerender. So for instance, if the user modified the value of Input1, both Input2 and Input3's values will be adjusted and rerendered.

The reason I rerender the template instead of just setting the values is that the template contains additional logic and elements that are rendered depending on the values (so for instance, certain values would result in an error message being rendered or an additional field being displayed).

So far so good, but this causes a focus problem. Take for example if the user modifies Input1 and then clicks on Input2. The onBlur will trigger, I'll update the values of Input2 and Input3 and then rerender the template. This in turn will cause the user's focus to be discarded, and they'll have to click on Input2 again.

I need a way to know that the user clicked on Input2 so that I can set the focus to it after the rerendering has been completed. As the onBlur event triggers before onFocus, I can't think of any way to do this.

Is there any solution other than bypassing the template rendering?

I had a similar problem. I solved it by delaying the "blur" event listener function with about 100ms, to allow the focus event on another input to fire before the blur handler starts rendering.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM