Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Safari: Prevent (or Control) Scroll on Input Focus

There are a lot of old questions sort of (but not quite) about this, but as I couldn't find anything modern, I thought I'd ask again with the hope of receiving a modern answer.

I am working on a hobbyist responsive web app, but I'm having trouble with input focus on iOS. I would like the input to scroll to just above the iOS keyboard on focus (or not scroll), but iOS wants to center that control no matter what.

In the attached GIF, you can see the behavior I'm seeing, and then I scroll at the end to indicate what I'd like to happen as soon as the focus event is triggered.

scrolling behavior

One thing I found that sort of works, but I'd like something better: the following code works, but has a noticeable delay between the scroll you see in the GIF and the window returning to the position I'd like it. Also, if I adjust the setTimeout() timing below ~400, it doesn't work. Does iOS have some block during its focus scroll bump?

element.addEventListener('focus', (e) => { setTimeout(() => { window.scroll(0,0) }, 500) });

 

Update #1

So far, the only solution I've tried that's worked is the following, which feels pretty janky (where scrollLock is defined elsewhere in focus and blur listeners):

document.addEventListener('scroll', (e) => {
    if (scrollLock && document.documentElement.scrollTop > 100) {
        document.documentElement.scrollTop = 100;
    }
});

All the solutions involving preventDefault() or window.scroll calls have not prevented the scroll pictured above, but actively monitoring the scroll and forcing it back to where I want it does work. Would love for this not to be the answer, however!

like image 967
Josh Hattersley Avatar asked Dec 05 '25 02:12

Josh Hattersley


1 Answers

One thing that worked for us is to call a scroll event 50ms after getting focus. So if you click into the text field a focus event is triggered. In that event we trigger a setTimeout(() => window.scrollTo(0,100), 50).

like image 92
Nico Avatar answered Dec 07 '25 15:12

Nico



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!