views:

22

answers:

1

Hi,

When tabbing to a form field that is below the bottom of the viewport (or typing in a textarea that overlaps the bottom), browsers usually automatically scroll up enough so that you can see the field. Is there a way to set the position the browser moves to?

This is an issue because I have a fixed position bar at the bottom of the page and so it covers up where the browser scrolls to and would like it to scroll up further.

Cheers

A: 

Sure, you could add a focus event handler to your inputs and check their position onfocus. If it's too close to the bottom, just bump the window scroll a bit until it's acceptable.

Below is how you could do it in jQuery:

// Constant amount of padding an element should be from the bottom of the window
var padding = 50;

// Add focus event to all your different form elements
$("input, textarea, select").focus(function(){

    // Check their position relative to the window's scroll
    var elementBottom = $(this).offset().top + $(this).height();
    var windowScroll = $(window).scrollTop();
    var windowBottom = windowScroll + $(window).height();

    if(elementBottom + padding > windowBottom){
        $(window).scrollTop(windowScroll + padding);
    }

});

You can see it in action here.

Edit: Typing in textarea

You could capture and check the position of the textarea during typing using the keydown event handler:

$('textarea').keydown(function(){
    // same logic as above to check textarea position relative to window
});
Pat
Hi Pat, thanks for the response, I did end up doing this. However there's also the fact that when typing in a textarea that overlaps the bottom of the viewport the window scrolls to the cursor so that it doesn't disappear. Would this be possible to change too?
Joel
Not a problem and sure it would be possible - see my edits for how you could do it.
Pat