Scroll page on text input focus for mobile devices?

34,152

Solution 1

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

Solution 2

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.

Solution 3

$('input, textarea').focus(function () {
    $('html, body').animate({ scrollTop: ($('input, textarea').offset().top - 10) }, 1);
    return false;
});
Share:
34,152
Evanss
Author by

Evanss

Updated on November 06, 2020

Comments

  • Evanss
    Evanss over 3 years

    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

  • brunodd
    brunodd about 9 years
    Thank you! Is there any option for scrolling on the middle of the page?
  • Stu Cox
    Stu Cox about 9 years
    document.body.scrollTop = $(this).offset() + (window.innerHeight / 2); maybe? But you’d want to ensure an on-screen keyboard doesn’t overlap the input (and you have no idea what crazy keyboard person X might use on device Y), so top is probably safer.
  • Siyah
    Siyah over 7 years
    Is this possible to do in Angular too?
  • Siyah
    Siyah over 7 years
    Is this possible to do in Angular too?
  • equiman
    equiman over 7 years
    you are missing ); at end
  • Stu Cox
    Stu Cox over 7 years
    @Siyah Angular is a framework rather than a DOM library, so normally you’d use jQuery for this kind of thing anyway (or just vanilla JS: youmightnotneedjquery.com/#on).
  • Gilad Barner
    Gilad Barner over 7 years
    Added missing );
  • Pochmurnik
    Pochmurnik almost 5 years
    Edit your post and use code formatting. Also consider adding any explanation to your code.