Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 634
Peter Craig Avatar asked Dec 03 '09 03:12

Peter Craig


People also ask

How to set tab focus in JavaScript?

Setting the value to “-1” also allows you to programmatically enable tab focus. Say you have an element that you don't want focusable on page load but after some event, you'd like to be focusable—you'd use tabindex=“-1” and the “. focus()” function to add that behavior.

Can divs receive focus?

Headings, paragraphs, divs, and various other page elements cannot receive focus. Elements that are focusable are normally ones that users can interact with, such as links and form controls. There's generally no need to set focus on something if the user can't interact with it.


3 Answers

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);
    }
});
like image 52
PetersenDidIt Avatar answered Oct 18 '22 18:10

PetersenDidIt


Same from above with 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');            
         }
     });
like image 31
Arun Prasad E S Avatar answered Oct 18 '22 16:10

Arun Prasad E S


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.

like image 1
jitter Avatar answered Oct 18 '22 18:10

jitter