Disable body scrolling on mobile devices in native browsers

When using the native browser on Samsung Galaxy S5 / S6, the following CSS code:

body {
  overflow: hidden;
}

does not successfully prevent the body from scrolling.

Is there a way to work around this issue?

Edit: As mentioned below, one workaround is to add overflow:hidden to the html tag as well. However, this causes the page to scroll to the top.

Is it possible to disable body scrolling without experiencing the side effect of the page automatically scrolling to the top once overflow:hidden is applied to html and body tags?

It's important to note that this issue occurs in the following environments:

Samsung Galaxy S5 (Android 5.0) Browser: Native;
Samsung Galaxy S6 (Android 6.0.1) Browser: Native;
iPhone 5S (iOS 8.4.1) Browsers: Chrome; Safari;
iPhone 6+ (iOS 9.3.2) Browsers: Chrome; Safari;

Answer №1

attempt

body {
    overflow:hidden;
    position:fixed;
    top:0;
    bottom: 0;
}

Answer №2

Css + Javascript solution:

Here is a CSS class that disables scrolling:

.lock-scroll{
    position: fixed;
    width: 100%;
    height: 100%;
}

And here are the JavaScript functions to handle scrolling and fix the scrollTop jump issue:

function disableScroll(elem){
    var lastScrollTop = $(elem).scrollTop();
    $(elem).addClass("lock-scroll");
    $(elem).css("top", "-" + lastScrollTop + "px");
}

function enableScroll(elem){
    var lastScrollTop = Number($('#wmd-input-39380954').css("top").match(/[0-9]/g).join(""));
    $(elem).removeClass("lock-scroll");
    $(elem).css("top", "0px");
    $(elem).scrollTop(lastScrollTop);
}

Disable scroll by target element

In your index.html file:

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
        </script>
        <style>
            body{
                  background-color:#333333;
                  color: white;
              }
              #modalView{
                  position: fixed;
                  width: 100%;
                  height: 100%;
                  left: 0;
                  top: 0;
                  background: rgba(0,0,0,0.6);
                  overflow: scroll;
              }
              #modalViewScroll{
                width: 300px;
                height: 200px;
                overflow: scroll;
                position: absolute;
                left: 0;
                right: 0;
                bottom: 0;
                top: 0;
                margin: auto;
                background: white;
                color: red;
              }
        </style>
    </head>
    <body>
        // Your content goes here
        // This section will be shown in the modal
        
        <div id="modalView">
            <div id="modalViewScroll">
                // Modal content with scrolling
            </div>
        </div>
        
        <script type="text/javascript">
            // JavaScript functions for handling scrolling
        </script>
    </body>
</html>

To avoid scrolling to top with click event fires

If you want to prevent scrolling to the top when a click event fires, add return false; after the click event like this:

Example:

<button onclick="openModal(); return false;">Open Modal</button>

To disable scroll in mobile browsers

To disable scrolling in mobile browsers, you need to set overflow:hidden for the <html> tag as well.

Example:

<html>
    <head>
        <style>
            html,body{overflow:hidden}
        </style>    
    </head>
    <body>
        // Your HTML body content
    </body>
</html>

Answer №3

One way to achieve a modal pop up is by using the Bootstrap framework. Simply copy and paste the following code into an HTML page:


 <!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Modal Pop Up Example</title;

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>


</head>
<body>

<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch Modal
</button>

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal Title</h4>
      </div>
      <div class="modal-body">
        <p>Your content here...</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

</body>
</html>

Answer №4

In my opinion, the key is to adjust the BODY position as relative in order to prevent it from scrolling to the top once you define it:

BODY {    
    width:100%;
    height:100%;
    overflow:hidden;
    position:relative;    
}

Answer №5

After trying numerous solutions, I finally cracked the code.

Here's the key snippet to insert into your HTML body:

body {
   overflow: hidden;
   overflow-x: hidden;
   overflow-y: hidden;
   position: fixed;
   top: 0;
   bottom: 0;
   left: 0;
   right: 0;
}

This method does the trick. It appears that some browsers disregard the overflow property but recognize the individual -x and -y values. However, solely using those values is insufficient. By utilizing the position fixed technique with all four directions set to zero, the desired outcome is achieved.

Answer №6

Consider including margin:0px !important within the body tag for optimal results

Answer №7

If you're looking to prevent body scrolling, consider using the npm package body-scroll-lock.

This package offers a cross-device solution by combining CSS and JavaScript techniques, ensuring functionality on iOS, desktop browsers, and other devices without relying on position: fixed.

With body-scroll-lock, you can lock body scroll while still allowing scrolling within a specific element. You can access the source code on the Github repository.

Check out a live demo to see it in action.

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

Passing a deconstructed object as a parameter for a function

I'm having trouble understanding the parameter const Posts in the code snippet below. As a newcomer to node/React, I'm not sure if it's a destructured parameter object or just an object being passed as a parameter. The functions getPosts an ...

Having trouble retrieving data from the API, can anyone help me figure out what I'm doing incorrectly?

Greetings! I am currently working on populating a recyclerview with data fetched from an API. The data includes information from a sub table nested within the main table. Below is the code for better understanding: When dealing with the API JSON, I encoun ...

Issue encountered: Next.js version 14, Tesseract.js Error: Module not found .../.next/worker-script/node/index.js'

While working with nextjs 14 and trying to extract text from an image using the tesseract.js node module, I encountered an error where the module was not found. The specific error message I received is as follows: Error: Cannot find module '...(projec ...

What is the process for making an Ajax request in Rails?

I'm attempting to send a variable through jQuery using the POST method, saving it in a controller, and then utilizing that same variable in Rails HTML to query a table. It seems like the variable isn't being passed to the controller. jQuery: v ...

Display a variety of body background images depending on the user's selection

Is it possible to change the background of the page when an option is selected from a dropdown menu? Additionally, can this be achieved with a smooth fade in and fade out animation? Here is a code example on CodePen. body ...

Looking to execute PHP scripts when a button is clicked? I've generated a lineup of upcoming workshops and added a registration button for each. Take a look at my code snippet below

Is there a way to execute php scripts when a button is clicked? I have created a list of upcoming workshops and added a registration button for each workshop. When the user clicks on the apply button, I would like to save their details in the database. B ...

When a table undergoes a dynamic reload, the formatting for the columns fails to display properly

After fetching image metadata from an API call, a table is dynamically generated on page load. Subsequently, when new images are uploaded, the function responsible for building the table is called again to include this new data. However, despite the CSS st ...

The sticky positioning feature seems to be malfunctioning exclusively on mobile devices

I have encountered an unusual issue while working on my cafe-shop menu. Despite finding a solution in a standalone HTML file, the menu doesn't function properly when inserted into one of the pages of my WordPress theme - specifically, it only works on ...

Overlaying div above vimeo player

I'm attempting to overlay a div on top of a Vimeo video, a task I anticipated would be straightforward but turns out to be more complex than expected. Below is the HTML code snippet: <div id="wrap"> <iframe id="video" s ...

Tips for retrieving information from a dynamically created form using VUE?

Welcome Community I am working on a parent component that includes a child component. The child component dynamically renders a form with various controls from a JSON object retrieved via a Get request using Axios. My goal is to be able to read and loop ...

Adjusting the text color based on the dynamically set background color

If I have a calendar where each entry has a unique background color assigned to it (one color per user), including both light and dark colors that users can choose from, how can I set the text color to match the background style? Where should I begin wit ...

I am looking to incorporate automatic scrolling functionality into my RSS Feed

I'm in the process of developing an RSS feed for my website. My expertise in JS/jQuery is limited, so any assistance would be greatly appreciated. After utilizing Google's Feed API and creating my own RSS Reader Widget, I realized that it lacked ...

Remove the PHP MySql record of the currently logged in user

I'm currently working on addressing an issue I've encountered. My goal is to remove a logged-in user from a MySQL database once they click a specific button. The code involved is named changepw.php <?php $servername = "localhost"; $username ...

Grabbing a section of a URL through a bookmarklet: A simple guide

Recently, I've been using this handy bookmarklet: javascript:currentUrl=document.location.href;document.location.assign(currentUrl+'embed'); This neat tool grabs the current URL, such as www.example.com/knZg_INW8fL/, and adds embed to it f ...

Access a specific JSON value using AngularJS

When using AngularJS to read a specific JSON value, I encountered the following issue: $http({method: 'GET', url: urlVersion}). success(function(data, status, headers, config) { console.log("success data " + status); $scope.ext = data.ve ...

The HTML password input continues to respond to key bindings, even when other inputs are not affected by the bindings

In the ongoing development of a legacy react application, I encountered keybindings that are causing unexpected behavior. For instance, pressing the "F" key triggers the full screen mode within the app. However, this keybinding is inadvertently active for ...

ever-evolving background-image with dynamic CSS styling

Being new to both PHP and Javascript, please excuse any mistakes in my explanation. I have information stored in a PHP array that I bring to my index page using the function below (located in a separate file called articles.php that is included in my index ...

Can conditional statements be utilized within a React component?

Using Material UI, the CardHeader component represents the top part of a post. If the post is created by the user (isUser = true), I would like to display two buttons on the post. Is this achievable? <CardHeader avatar={ <Avatar sx={{ ...

s3 is having trouble uploading the file and is returning an error stating SignatureDoesNotMatch

I'm experiencing an issue while attempting to upload images to my s3 bucket in aws. The error message SignatureDoesNotMatch keeps appearing. Below is the code I am using to upload the file/image: FrontEnd const file = e.target.files[0]; const fileP ...

Having trouble with accessing properties like `d3.svg()`, `d3.scale()` and other features of d3js within an Angular 2 environment

Struggling to incorporate d3.js into angular2. Below is the command I used to install d3 in Angular2: npm install --save d3 install --save-dev @types/d3 This is how my package.json appears: { "name": "my-app", "version": "0.0.0", "license": "M ...