user3038754
user3038754

Reputation: 195

position: sticky doesn't work when virtual keyboard is open in Safari

Position sticky doesn't work when virtual keyboard is open in Safari

I've tried using position: -webkit-sticky.

Expected behavior in non-Safari webkit browsers (Chrome, Firefox, Opera)

.sticky {
  background-color: red;
  position: sticky;
  position: -webkit-sticky;
  bottom: 0;
}

Steps to reproduce:

  1. Open https://codepen.io/wmsmacdonald/pen/vYBVVRL in Safari on iOS
  2. Scroll to bring white screen into viewport
  3. Click text input to focus

Expected: Red footer should stick to bottom of screen even when virtual keyboard is open Actual: User must scroll down with keyboard open in order to see the red footer

Upvotes: 5

Views: 4019

Answers (2)

Yuxiang Yang
Yuxiang Yang

Reputation: 61

let pendingUpdate = false;
const viewportHandler = (event) => {
    if (pendingUpdate) {
        return;
    }
    pendingUpdate = true;

    requestAnimationFrame(() => {
        pendingUpdate = false;
        const layoutViewport = document.querySelector('.sticky');
        layoutViewport.style.transform = "none";
        if (layoutViewport.getBoundingClientRect().top < 0) {
            layoutViewport.style.transform = `translate(0, ${-layoutViewport.getBoundingClientRect().top}px)`;
        }
    });
};
window.visualViewport.addEventListener("scroll", viewportHandler);
window.visualViewport.addEventListener("resize", viewportHandler);

The pendingUpdate flag serves to prevent multiple invocations of the transfrom that can occur when onresize and onscroll fire at the same time. Using requestAnimationFrame() ensures that the transform occurs before the next render.

Upvotes: 6

user3038754
user3038754

Reputation: 195

This is expected behavior in Safari as of October 2019:

https://bugs.webkit.org/show_bug.cgi?id=202120

A workaround to make it consistent with other rendering engines would be to use the Visual Viewport API to get the visual viewport height and fix the element to the bottom using position: absolute. However, the Visual Viewport API only has support in Safari 13.

Upvotes: 5

Related Questions