Peter Craig Peter Craig - 3 months ago 18
Javascript Question

input on focus or tab key pressed, move to center of screen

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?

Answer

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);
    }
});
Comments