views:

325

answers:

2

I have a number of form fields spanning over the page fold. When pressing the "tab" key to step through each input/select field it sits the next field on the bottom of the page fold.

A few of my fields have tool tips, validation responses and auto suggest boxes that appear below the field. When tabbing to the field, you can't see these elements below the page fold.

Is there a javascript or jQuery script that can vertically centre the screen around a focussed input/textarea/select/button field instead of aligning to the bottom?

A: 

You can just bind to the focus event and then calculate the offset of the field 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);
    }
});
PetersenDidIt
I think this is the simplest solution to my question but as commented, the action is not standard and could be an annoying action in most cases - the question needs to be slightly redefined to have a practical use for this solution.
Peter
Doing a few checks, it gets the values right but window or document scrollTop() doesn't want to play ball... I've changed this to the div id (#div).scrollTop which almost does it but isn't as consistent as I'd expect body or window to be.
Peter
A: 

Easiest thing would be to include the jQuery ScrollTo plugin and the jQuery Viewport plugin.

Then wrap every input + related other elements (validation response, ....) in a div.

On focus check if the div is completely visible, if not use scrollTo. Done.

Of course this is a bit of a bloat but if you can live with the 2 more dependencies and an additional ~4kb this should work without doing the calculations yourself.

jitter