6

I'm trying to prevent scroll page when user tap on input:

<pre class="js-parent">
  <input value="tap to focuss" readonly>
</pre>

$("input").on("focus", function(e) {
  e.preventDefault();
  e.stopPropagation();
});

$("input").on("click", function(e) {
  e.preventDefault();
  e.stopPropagation();
  this.setSelectionRange(0, 9999);
});

Few problems:

1) when user click on input page scroll to element (to the top of the page)

2) when focus is active, parent block lose position: fixed

demo

demo with code

Pavel
  • 2,103
  • 4
  • 23
  • 41

2 Answers2

4

You can trick safari into thinking that the current focused input is at the top of the page, so that no need to scroll down, by following trick:

$(document).on('touchstart', 'textarea, input[type=text], input[type=date], input[type=password], input[type=email], input[type=number]', function(e){

            var intv = 100;
            var $obj = $(this);

            if (getMobileOperatingSystem() == 'ios') {

                e.stopPropagation();

                $obj.css({'transform': 'TranslateY(-10000px)'}).focus();
                setTimeout(function(){$obj.css({'transform': 'none'});}, intv);
            }
            return true;
        });

You can find more details in following thread, which shows how to do this for android os, too.

jquery mobile How to stop auto scroll to focused input in Mobile web browser

danronmoon
  • 3,814
  • 5
  • 34
  • 56
Codemole
  • 3,069
  • 5
  • 25
  • 41
0

Here is a Vanilla JS version based on the first answer. It prevents IOS & mobile Safari from scrolling the screen when the soft keyboard is opened via the focus event created when clicking into an input.

It works perfectly in iOS 15.2.1

It also works very well with the 'focus' event.

element.addEventListener('touchstart', (event) => {
    event.stopPropagation();
    element.style.transform = 'TranslateY(-10000px)'
    element.focus();
    setTimeout(function () { element.style.transform = 'none' }, 100);
});
  • I will have to give this a try. I have a sticky calendar selector that stays as a person is scrolling down the page but the original position is at the top of the page then as the user scrolls, I position it sticky to the top of the browser window. Of course Safari decides it is going to be smarter than the user and decide for them in Apple fashion, and scrolls the user clear back to the top of the page when the user wants to update the calendar date to the original position in the HTML not keeping manipulated DOM position. – ClosDesign May 18 '22 at 21:57