Search code examples
javascripthtmlcsskeyboard

Prevent virtual keyboard from pushing content up


I have website; a background image with an input. When I press on the input on my phone, the keyboard opens an everything gets pushed up. I would like instead the content to stay in place and keyboard just to go over the content without affecting(moving) it. I saw this solution:

input.onfocus = function () {
    window.scrollTo(0, 0);
    document.body.scrollTop = 0;
}

But it doesn't seem to work. I'm looking forward to your answers!


Solution

  • You can take a look at this StackOverflow post, but I'll summarize the most useful parts for you:

    Start off with the input's CSS as position: fixed;. When in focus, change it to absolute. Here is an example with JS:

    if (document.getElementById("fixed") == document.activeElement) {
        document.getElementById("fixed").class += "absolute"
    }
    

    Of course, that relies on CSS:

    #fixed {
        ...
        position: fixed;
    }
    #fixed.absolute {
        position: absolute;
    }
    

    I hope this helps!