Enter focus or tab key pressed, move to center of screen

I have several form fields spanning a page. When you press the tab key to go through each input / selection field, it selects the next field at the bottom of the page.

Some of my fields have tool tips, test answers, and auto-suggestion windows that appear below the field. When you move to the field, you cannot see these elements under the page layer.

Is there a javascript or jQuery script that can vertically center the screen around the input focus / textarea / select / button instead of aligning it at the bottom?

+7
javascript jquery input
source share
3 answers

You can simply snap to the focus event, and then calculate the field offset and center it on the screen.

$(':input').focus(function(){ var center = $(window).height()/2; var top = $(this).offset().top ; if (top > center){ $(window).scrollTop(top-center); } }); 
+14
source share

The easiest way would be to enable the jQuery ScrollTo plugin and jQuery Viewport .

Then wrap each entry + related other elements (validation answer, ....) in a div.

In focus, check if the div is fully visible if you don't use scrollTo . Done.

Of course, this is a little bloated, but if you can live with two more dependencies and an additional ~ 4kb, this should work without doing the calculations yourself.

+1
source share

The same on top with a smooth scroll effect

  $(':input').focus(function () { var center = $(window).height() / 2; var top = $(this).offset().top; if (top > center) { $('html, body').animate({ scrollTop: top - center }, 'fast'); } }); 
+1
source share

All Articles