Using preventDefault will stop the page from scrolling

I have developed a responsive website that allows users to bookmark it on their home screen. It would be ideal for the site to prevent the screen from displaying any grey background when scrolling to the top or bottom on tablets and phones, rather than snapping back abruptly.

I understand that using 'preventDefault' on the body can achieve this, but at present, it unfortunately disables scrolling altogether.

Below is the snippet of javascript code:

$(document).ready(function(){
  document.ontouchmove = function(e){e.preventDefault();}
});

And here is how the html call looks like:

<body ontouchmove="touchMove(event)"> 

Answer №1

To optimize the performance, it is recommended to capture the event and execute preventDefault only when it reaches a specific viewport or scrollTop position. Below is an example of how this can be implemented:

function getScrollTop(){
    if(typeof pageYOffset != 'undefined'){
        //most browsers
        return pageYOffset;
    }
    else{
        var body = document.body; //IE 'quirks'
        var docElement = document.documentElement; //IE with doctype
        docElement = (docElement.clientHeight) ? docElement : body;
        return docElement.scrollTop;
    }
}

You can then use the following code snippet to call preventDefault only when the scrollTop is at the top:

$(document).ready(function(){
      document.ontouchmove = function(e){ 
          if (getScrollTop() !== document.scrollTop) {
             e.preventDefault();
          }
     }
});

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

Having issues with default sorting and searching not functioning in Datatables with Angularjs

Utilizing a directive to facilitate database building once ng-repeat has completed: app.directive('repeatDone', function() { return function(scope, element, attrs) { if (scope.$last) { scope.$eval(attrs.repeatDone); ...

The request for `/` cannot be fulfilled while serving an Angular application with Express and Node.js

I've been attempting to host an Angular application using Node.js, but I keep encountering the error message "Cannot GET /" displayed on the page. Despite trying various solutions, I have been unable to resolve this issue. Does anyone have any suggest ...

Adjust the size of a div element with JavaScript

Currently, I am facing a challenge with resizing a div with the id="test". My goal is to adjust the size of the div based on the height of the browser window subtracting 80px so that the element fits perfectly within the visible space without req ...

Utilizing React to highlight buttons that share the same index value upon hover

I have some data in a JavaScript object from a JSON file, where certain entries have a spanid (number) while others do not. I've written React code to highlight buttons with a spanid on hover, but I'm looking for a way to highlight or change the ...

"JavaScript Object Notation ajax request results in an undefined

I've been searching through SO and various websites in hopes of finding a solution, but nothing seems to address my specific issue. The task at hand is to retrieve a value from a function. Currently, the data is successfully fetched from the JSON cal ...

Using Vue to create a component that binds an array as its data source

Having trouble binding an array as a variable and accessing it in the child component, resulting in the variable being undefined. Is there a way to pass an array from a view to a component so that the component can use this array to create a child componen ...

Three.js emits a selection list

I'm currently working on creating a picking ray to determine if my 3D body in three.js has been clicked. I've tried following some advice from different sources like this post and this thread. This is the code I have so far: function checkClick ...

Creating a front-end angular application with npm and grunt commands

Hello there! This marks my first question, so please bear with me if it's a bit unclear. I'm fairly new to application development and currently working on an AngularJS app using Grunt. My query revolves around the build process I've execut ...

Discover Your Location in the Web Browser

My webpage includes the following JavaScript code to obtain the user's location: state.currentTimer = navigator.geolocation.watchPosition(success, error, { enableHighAccuracy: true, maximumAge: 5000 }); The page is designed to be accesse ...

Identifying issues in jQuery code - What could be causing this error?

My jQuery code is not responding at all, not even showing an error! I'm not sure why, but here is the jQuery Code I'm using: /* This part is working fine */ $(".add-blog .blog-add-form .add-article .input-group select").on("change", function() ...

Creating a click-away listener feature in your Next js application

I have a reusable component called DropDown and a custom hook called useClickOutside. I am utilizing the context API to manage multiple dropdowns with unique ids. Code for useClickOutside import { useEffect, useRef } from "react"; import { toUSV ...

Creating a barrier between objects in motion

I need assistance with creating a connection between two dynamic vertices in my project. The information for each vertex is stored within an object named object, containing the position data as a THREE.Vector3. To create the line connecting these vertices ...

Please ensure the public_id parameter is included and provide the necessary value for the imageId when working with Cloudinary

I am in the process of developing a website where users can share insights and comments on novels they have read. Users have the option to include images of the novel with their posts or not. If an image is included, the post schema requires attributes im ...

Is there a way to eliminate a certain word from being used?

My goal is to mask inappropriate words with asterisks ***. However, I've encountered a challenge when the offensive word is part of another word that shouldn't be replaced. for(var i = 0; i < forbidden.length; i++) { if(textBoxValue.searc ...

Using AngularJS to iterate through a list of objects and apply filters based on the

Is it possible to iterate over objects and check their properties? { Obj1 : { visible : true, value : 2} Obj2 : { visible : false, value : 4} Obj3 : { visible : true, value : 6} } HTML: <ul ng-show="data.templates.attachments"> <li n ...

Connecting node.js to a MySQL database on a WAMP/XAMPP server: A step-by-step guide

As a PHP programmer, I am experienced with WP, CI, and OC. However, I am a complete beginner when it comes to node.js and how to connect MySql with WAMP/XAMPP in a step-by-step method. If I were to set up a live server for this project, what would be the ...

Configuring Monaco Editor in React to be in readonly mode

Here is a code snippet to consider: import React from "react"; import Editor from "@monaco-editor/react"; function App() { return ( <Editor height="90vh" defaultLanguage="javascript" defa ...

Troubleshooting npm start error: "Cannot find module: Error: Unable to resolve..." when relocating webpack/react files

Initially, my project was functioning perfectly and I could easily access my web page on localhost:8080 using Chrome. In an attempt to learn something new, I organized all my files into a folder named 'dir copy' instead of just 'dir'. O ...

Utilizing AngularJS to target DOM elements within an ng-repeat loop

I currently have my ng-repeat set up within a div tag: <div ng-repeat="x in names"> <h1>{{x.product}}</h1> <h2>{{x.brand}}</h2> <h3>{{x.description}}</h3& ...

Having difficulty retrieving the specific Laravel validation error message through AJAX

In my Laravel project, the error message I am encountering is: {message: "The given data was invalid.", errors: {oData: ["validation.required"]}} errors: {oData: ["validation.required"]} message: "The given data was invalid." I am not trying to display ...