How do I stop the browser from jumping to the focused field?

3.2k views Asked by At

I have a form inside a container with overflow:hidden, and I'm changing its className, where each class makes its top-margin to show the proper focused field with focus().

So the jQuery only applies the className. No animation other than webkit is involved.

The problem is that before the animation occurs, the form MOVES inside the container to reveal the hidden field. No value appears changed in the inspector: either top, top-margin, top-padding remain unchanged.

I tried preventDefaults(); on the focused fields, no success.

Here is a fiddle to show the case.

http://jsfiddle.net/dNk9v/

UPDATE: I want to make clear that when "tabbing" to the next field, it DOES go there, but the css animation happens on top of it, and the form either jumps no animation or just animates ALONG with the already-happened scrolling/revealing so the expected field ends up outside of the container.

Clicking the legend tag tabs works as expected. I'll try preventing defaults for the keydown events, rather than the focus ones, and I'll keep you updated.

1

There are 1 answers

1
stevero On BEST ANSWER

Per this post, it seems like a rather complicated problem: https://forum.jquery.com/topic/chrome-bug-or-how-do-i-prevent-a-form-field-to-scroll-the-container-when-focused

I have managed similar issues by manually managing the tabindex attribute of the inputs. This removes the unwanted pseudo-scrolling, but also removes the ability to tab to inputs outside the viewport. If you are willing to live with that, then you can easily add some code to your click handlers to add or remove tabindexes:

$(inputEl).attr('tabindex', -1);  // removes tabbing
$(inputEl).attr('tabindex', 1);   // restores tabbing

Remove the tab indexes from inputs outside the viewport, and restore them for visible inputs.