Search code examples
ioscssiphonegoogle-chromesafari

How to make fixed-content go above iOS keyboard?


I can only find questions where people have the opposite problem.

I want my fixed content to go above the iOS keyboard. Image of the problem:

fixed content goes below keyboard on ios

I want iOS to behave like Android.

Is there a simple way to achieve this?

Parent element css:

.parent{
    position:fixed;
    top: 0;
    left 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
}

Button css:

.button{
    position:fixed;
    left 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 5rem;
}

Solution

  • We can use VisualViewport to calculate keyboard height. So we can set fixed-content pos correct.

    Small demo: https://whatwg6.github.io/pos-above-keyboard/index.html

    Github Repo: https://github.com/whatwg6/pos-above-keyboard

    Code snippet:

      const button = document.getElementById("button");
      const input = document.getElementById("input");
      let height = window.visualViewport.height;
      const viewport = window.visualViewport;
    
      window.addEventListener("scroll", inputBlur);
      window.visualViewport.addEventListener("resize", resizeHandler);
    
      function inputBlur() {
        input.blur();
      }
    
      function resizeHandler() {
        if (!/iPhone|iPad|iPod/.test(window.navigator.userAgent)) {
          height = viewport.height;
        }
        button.style.bottom = `${height - viewport.height + 10}px`;
      }
    
      function blurHandler() {
        button.style.bottom = "10px";
      }
      html,
      body {
        margin: 0;
        padding: 0;
      }
    
      #button {
        position: fixed;
        width: 100%;
        bottom: 10px;
        background-color: rebeccapurple;
        line-height: 40px;
        text-align: center;
      }
    <input
      type="text"
      inputmode="decimal"
      value="0.99"
      id="input"
      onblur="blurHandler()"
    />
    <div id="button" onclick="inputBlur()">Button</div>

    Problems: https://developers.google.com/web/updates/2017/09/visual-viewport-api#the_event_rate_is_slow

    Why not innerHeight?: Iphone safari not resizing viewport on keyboard open