Tuesday, December 12, 2017

Custom scrolling on iOS (and all mobile devices) when input is focused

Leave a Comment

The problem:

When the input is selected I want the screen to scroll so that the focused input is right at the top of the screen.

I want this to work on iOS and all other mobile devices.


This is what happens currently on iOS:

enter image description here


This is what I want to happen... Notice where the page scrolls to:

enter image description here


The code I'm currently trying out is:

$('#input').on('focus focusin', function(e) {     e.preventDefault();     $('html').animate({         scrollTop: $('#anchor').offset().top     }, 300); }) 

This code works great on desktop, but as soon as I load the page up on my iPhone, it stops working completely and the default scroll behaviour takes over—as seen in the first gif.

2 Answers

Answers 1

So you just need it to scroll so the top of the input becomes the top of the screen?

I have added 2 pixels gap above the input so that you can see the border at the top of the input still.

$('#input').on('focus', function(e) {     e.preventDefault();     $('html, body').animate({         scrollTop: $(this).offset().top-2;     }, 1000); }) 

Answers 2

Figured out the problem finally!

After hours and hours of mucking around, I figured out that the problem wasn't the code. The code shown in my question worked perfectly.

The problem happened to be my local testing environment (python manage.py runserver 0.0.0.0:8000 in command prompt).

I still haven't pinpointed the reason. I have however determined that I'm using Django 1.11.4 and jQuery 3.1.1 on both production and local testing environments. So why this problem would occur is beyond me.


My best guess is that there is some incompatibility between jQuery and Django's local testing server. 🤷

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment