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

Employing PHP to iterate through and separate items into disparate divs

For my project, I need to loop through 12 items and separate them into different divs. Specifically, I want to group 0 and 1 together in one div, have 2 in its own div, 3 and 4 in another div, 5 in a separate div, and so on. <!-- Grouping 0 and 1 --> ...

I want to know how to move data (variables) between different HTML pages. I am currently implementing this using HTML and the Django framework

I am currently working on a code where I am fetching elements from a database and displaying them using a loop. When the user clicks on the buy button, I need to pass the specific product ID to another page. How can I retrieve the product ID and successful ...

Design a visually stunning image grid with the use of Bootstrap 4

I am having difficulty creating an image grid with consistent spacing between columns, like shown in the image below: https://i.sstatic.net/azsxa.jpg The issue I am facing is aligning the right margin (red line), as illustrated below: https://i.sstatic. ...

Encountering difficulties in populating mongoose document following a model query

Hi everyone, this is my first time posting on SO so I'm hoping for some positive outcomes. I've been using Mongoose in a current project without any issues until now. The problem arises when trying to populate object references after querying fo ...

Tips for smoothly fading out a preloader

I found this script on the internet and implemented it, but I am having trouble with the fadeout effect. I really want a seamless and smooth fadeout animation. var loader = document.getElementById('spinner'); window.addEventListener("load", ...

The output of new Date() varies between app.js and ejs

app.get("/test",function(req,res){ var d = new Date(); res.send(d); }); When I access mydomain/test, it displays the output "2019-03-19T04:50:47.710Z" which is in UTC. app.get("/testejs",function(req,res){ res.render("testejs");}); Below is the content ...

What is the best way to declare a variable within a VueJS v-if condition without it being visible?

In my code, I have a specific template that is displayed when a certain condition is met using a v-if statement. In this template, I need to set a variable to N/A, but I am struggling with how to accomplish this simple task. <span v-if="se ...

The on-screen keyboard using JQuery and CSS is not working properly on an HTML redesign

UPDATE - Check out the modified version here: https://codepen.io/anon/pen/wZQjQy Here is the original for reference: https://codepen.io/anon/pen/YMRLBN (had to utilize CodePen, as simply adding a snippet here doesn't link the CSS) I essentially copie ...

Emphasize today's date on the w3widgets adaptable calendar

While developing a website featuring a calendar to showcase events, I came across w3widgets, which proved to be quite helpful. However, I encountered an issue when trying to highlight the current date on the calendar. It seems that the calendar only highli ...

struggle to locate / Node.js Error

I followed the tutorial located at and implemented the following code. // Module dependencies. var application_root = __dirname, express = require( 'express' ), //Web framework path = require( 'path' ), //Utilities for dealing with fi ...

Is there a way to determine if a browser's network activity is inactive?

Within an angularJS application, a noticeable delay can be experienced between the user and the server (potentially due to limited bandwidth), resulting in a wait time of approximately 2-500ms when loading a new page. I am considering implementing a metho ...

What is the best way to retrieve all objects from this data model?

I am looking to collect all the Model Objects from the data structure provided below. const PRODUCTS = [ { brand: 'Audi', allSeries: { serie: 'A3', allModels: [ { model: ' ...

Angular is unable to eliminate the focus outline from a custom checkbox created with Boostrap

Have you noticed that Angular doesn't blur out the clicked element for some strange reason? Well, I came up with a little 'fix' for it: *:focus { outline: none !important; } It's not a perfect solution because ideally every element sh ...

The error occurs when Facebook and Twitter iframes are attempting to access and set 'document.domain'

When attempting to add Tweet and Facebook Like buttons to the project I'm working on, everything appears to be functioning properly. However, upon clicking the buttons, a JavaScript error occurs: Unsafe JavaScript attempt to access frame with URL htt ...

The discord.js TypeScript is throwing an error stating that the 'index.ts' file is missing when trying to run 'ts-node index.ts'

I have been working on creating a discord bot using discord.js and TypeScript. However, when I attempt to start the bot by running 'ts-node index.ts', I encounter the following error: Error: Cannot find module 'node:events' Require stac ...

Removing commas and non-numeric symbols from a string using JavaScript

Stripping both a comma and any non-numeric characters from a string can be a bit tricky, especially with RegExs involved :). Is there anyone who could provide assistance on how to achieve this? I need to remove commas, dashes, and anything that is not a ...

I am experiencing difficulties with my custom font not functioning properly

I've experimented with the following code: @font-face { font-family: Jua; src: url('/fonts/jua.ttf'); } @font-face { font-family: Jua; src: url('..../fonts/jua.ttf'); } @font-face { font-family: Jua; src: url('.../fonts/jua.t ...

Secure Access: Passport.js User Verification & Authorization

Recently, I successfully developed my first User login and authentication system using Passport.js. While the system works as intended, I am struggling to fully comprehend the code itself despite reading numerous articles and examples online. I would great ...

Tips for selecting specific elements from an array with jquery

Is there a way to efficiently fetch specific elements from an array using jQuery? For example, if we have an array like this: var arr = [Obj1, Obj2, Obj3, Obj4, Obj5, Obj6] And we want to select objects with index 3 and 5. Is there a function or method t ...

Incorporating and designing a side button using jQuery Mobile

I'm working on adding a button to the left side of the screen that is round (but not necessarily) and partially visible, with a visually appealing design. This button will allow users to open a side menu panel. Below is the HTML code for the button: ...