Prevent page from refreshing on mobile devices using JavaScript

I have been attempting to prevent page refresh on a mobile device through touch scroll events. After researching online, I came across the following method:

/*
w = flag indicating if pageYOffset was 0 before attempting to scroll below it
h = last pageYOffset value
*/
function disablePageRefreshFacility() {
    let w,h=0;
    document.addEventListener('touchstart',function(e) {
        if(e.touches.length!=1) return;
        h=e.touches[0].clientY; w=window.pageYOffset===0;

        // testLabel is a DOM element used to display the current pageYOffset - for testing purposes     
        testLabel.innerHTML=window.pageYOffset;
    },false);
    document.addEventListener('touchmove',function(e) {
        let y=e.touches[0].clientY,d=y-h; h=y;
        if(w) { w=0; if(d>0) return e.preventDefault(); }
        if(window.pageYOffset===0&&d>0) return e.preventDefault();
    },false);
}

The page only contains a testLabel DIV and sets the

document.body.style.height="60000px"
for testing.

The problem at hand:

  • When the page is NOT zoomed, the pageYOffset provides the correct scrolling value according to the page.
  • However, when the page IS zoomed, the value remains at 0 until a certain scroll point which is currently difficult to detect.
  • If the
    document.body.style.height="60000px"
    line is removed, making the body unscrollable, scrolling the page while zoomed does not update the pageYOffset value.

Additional information:

  1. Tested on an Android browser.
  2. Pure JavaScript is utilized with no framework involved.
  3. The test is performed on touchstart - therefore, the pageYOffset value is obtained after the last scroll event.

Summary of Issues

  1. The touchmove event does not trigger when the page is zoomed, unless the initial innerHeight boundary is exceeded (before zoom).
  2. The issue of page refresh prevention has not yet been resolved.

A solution related to pageYOffset (or an alternative approach) would greatly assist in tackling the page refresh problem. Any alternate solutions are welcome, as I am puzzled why the touchmove event fails to trigger despite the page being "scrolled" (even while zoomed).

Answer №1

body {               
  overscroll-behavior: contain;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determine if checkboxes exist on a webpage using jQuery

I am facing a situation where a form is dynamically loaded via ajax. Depending on the parameters passed to retrieve the form, it may or may not contain checkboxes. I am looking for a way to verify the presence of checkboxes on the page and prompt the user ...

Is the max and min-width being properly set by the keen-slider__slide class in keen-slider?

Check out my code snippet below: import React from 'react' import { useKeenSlider } from 'keen-slider/react' // Styles import 'keen-slider/keen-slider.min.css' interface Props { children: any } // const animation = { du ...

How can I resolve the "web page not found" error when using jQuery .replace()?

Working on HTML and javascript/jquery scripts, I have encountered a peculiar issue. My script utilizes a for-in loop to iterate through a JavaScript object, substituting specific patterns in HTML-formatted lines with data from the object using jQuery .appe ...

Acquiring the root URL with the $location service in AngularJS

I am facing a situation where I have a specific URL structure like the one shown below. http://localhost:8080/test#/users/list Upon further investigation, I discovered the following information: $location.url() returns -> "users/list" $location.path( ...

The example in the MUI x-data-grid documentation always seems to fall short of expectations

I followed the code from the material-ui library documentation located at this link: https://mui.com/x/react-data-grid/layout/#flex-layout My aim is to set up a flex layout on my project, I went through the steps mentioned in the documentation but keep ...

Generate a Customized Modal for a Memo Capturer Program

I am currently developing a basic note-taking application using vanilla JavaScript. I want the program to add notes with a modal that displays the text when clicked. However, my current implementation adds the note below the input box and includes the moda ...

Encountered an issue while installing the "sharp" module on MAC M1

When I run npm run dev (gatsby develop) on my MacBook Pro M1 chip, it exits with the error message: Error: Something went wrong installing the "sharp" module However, when I run npm run dev on a MacBook Pro with an Intel chip, everything works fine. I&ap ...

Testing Async operations in the browser with Mocha and Chai

I'm having trouble running async tests with mocha. Below is the snippet of my code: describe('Brightcove Wrapper',function(){ describe("#init()", function() { it("Should inject the brightcove javascript", function(callback){ ...

Creating JSON data that is completely valid using client-side JavaScript

I've been working on creating a JSON explorer/editor. Successfully managed to parse the initial JSON into the div and customize the formatting. Here's the function I utilize to loop through the initial JSON: _iterate(_tab, raw_json){ var tab ...

Place the retrieved data from the API directly into the editor

I've integrated the LineControl Editor into my app and everything is functioning perfectly, except for when I attempt to insert text into the editor. Here's the link to the LineControl GitHub page: https://github.com/suyati/line-control/wiki Fo ...

Adjust the size of a Div/Element in real-time using a randomly calculated number

Currently, I am working on a script that is designed to change the dimensions of a div element when a button on the page is clicked. The JavaScript function connected to this button should generate a random number between 1 and 1000, setting it as both the ...

Angular7 is throwing an error saying it cannot read the property 'post' of undefined

Looking to create a custom validation in Angular 7. Here is the code snippet: CheckUserNameExisit(control: AbstractControl): { [key: string]: any } { console.log('in functions') return new Promise(resolve => { let httpClient: HttpClient ...

Having trouble submitting a date input form generated with vuejs on Safari browser

I am a huge fan of Vuejs and it's my go-to at work. The other day, I came across a rather perplexing scenario. If you have any insights into this, please do share. Here is the code in question: <script setup lang="ts"> import { ref ...

generate radio buttons and corresponding labels in real-time

I am trying to automate the creation of elements for each record retrieved from my webservice. <label for="ZAALID_1">Zaal 1</label> <input id="ZAALID_1" type="radio" name="RESERVATIE.ZAALID" value="1" MSGCHECKED="~IF(CHK ...

Instructions for connecting a camera to a bone or vertices on a model in A-Frame without influencing its rotation

How can I attach a first-person camera to the head of an animated GTLF model? My plan is to eliminate the model's head and combine the neck into one vertex to avoid obstructing the camera. I am curious about the process of attaching my camera to the v ...

Incorrect Date Returned by Sequelize (-1 Day Difference)

My issue revolves around the birthdate field in one of my tables, which has a Data Type of Date. However, when attempting to export the data through an Express app, the date is transformed into a day earlier than it should be. For instance, a birthdate of ...

Unable to locate the name 'Cheerio' in the @types/enzyme/index.d.t file

When I try to run my Node application, I encounter the following error: C:/Me/MyApp/node_modules/@types/enzyme/index.d.ts (351,15): Cannot find name 'Cheerio'. I found a suggestion in a forum that recommends using cheerio instead of Cheerio. H ...

Using jQuery to Activate Genuine Events

Is it true that jQuery's trigger() only executes event handlers bound with jQuery? I have some modules that utilize native browser event binding. Although the solution from works for me, I'm curious if there is a built-in way in jQuery to handle ...

Creating a dropdown selection that allows for both multiple and single choices

I am working on a JavaScript function that dynamically changes the display of a DIV based on the selection made in another dropdown. The first dropdown contains options for one, multiple, or none. When 'single' is selected, I want it to change th ...

Automatically calculate the product of two columns in a gridview

Greetings, I am currently working on a project that involves calculating values from two textboxes within a gridview and displaying the result in a third textbox using JavaScript. The calculation should occur as soon as a value is entered into the second ...