Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll page on text input focus for mobile devices?

Im making a mobile optimised site with a text input which filters a list as you type. Its similar to this: http://jquerymobile.com/test/docs/lists/lists-search.html

For phones, it would be a usability benefit if when you selected the input the page scrolled down so the input was at the top of the page. That way as much of the list below would be visible as you type. Is this possible and/or does anyone have experience doing it? Thanks

like image 465
Evanss Avatar asked May 23 '12 12:05

Evanss


2 Answers

Agreed - that'd be nice for usability.

If you're using jQuery, this should do the trick:

$('#id-of-text-input').on('focus', function() {
    document.body.scrollTop = $(this).offset().top;
});
like image 128
Stu Cox Avatar answered Sep 19 '22 14:09

Stu Cox


A better solution would be:

$('#id-of-text-input').on('focus', function() {
   document.body.scrollTop += this.getBoundingClientRect().top - 10
});

Because offsetTop (or .offset().top if using Jquery) returns the distance from the first positioned parent, whereas you need the distance from the top of the document.

getBoundingClientRect().top returns the distance between the current viewport position to the element, u.e. if you're scrolled 300px below the element, it would return -300. So adding the distance using += would scroll to the element. -10 is optional - to allow some space at the top.

like image 40
Gilad Barner Avatar answered Sep 17 '22 14:09

Gilad Barner