Auto-scroll browser to tab through form elements

When pasted into a form field that is below the bottom of the viewport (or enter a text area that overlaps the bottom), browsers usually automatically scroll enough so you can see that field. Is there any way to set the position the browser is moving to?

This is a problem because I have a fixed position at the bottom of the page, and therefore it closes where the browser scrolls, and she would like it to scroll further.

Greetings

+3
source share
1 answer

, . , , .

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

});

.

: textarea

:

$('textarea').keydown(function(){
    // same logic as above to check textarea position relative to window
});
+1

Source: https://habr.com/ru/post/1761096/


All Articles