Stop the body from scrolling when dialog is open on a mobile screen

I am encountering an issue on a mobile screen where I am displaying a dialog that is longer than the screen size, causing it to scroll.

The problem arises when scrolling past the bottom of the dialog (I am utilizing Bootstrap 3) as instead of stopping, it begins to scroll the underlying body. Despite trying all suggested solutions from this resource, the issue still persists!

For a live demonstration of the problem, check out the JSbin link below

http://jsbin.com/EdAhAsU/1/

Please note: To replicate the problem, access the link on any mobile device and try scrolling past the end of the dialog. I have tested this on both Android and iPhone with no success.

Thank you for your help!

Answer №1

Give this a try:

body {
    left: 0;
    -webkit-overflow-scrolling: touch;
    position: fixed;
    top: 0;
    width: 100%;
}

This solution worked well for me (check it out at http://jsbin.com/aXoMaGo/2) when using Safari/Chrome on iOS 7, and it also adds a nice bounce effect to the modal.


For a final working solution (even when the dialog is closed): https://jsbin.com/aXoMaGo/6. The only drawback is that it scrolls to the top of the page each time the modal is closed.

Answer №2

To simplify the process, consider implementing the overscroll-behavior CSS property onto the popup box.

.modal {
overscroll-behavior: contain;
}

This functionality was introduced to CSS with the intent of addressing scenarios like this one.

Answer №3

Dealing with a comparable problem in the past, I found that using overflow:hidden tends to work well for desktops. However, for mobile devices, it's necessary to also implement position fixed. To achieve this, simply add a ".noscroll" class to the body element when your dialog is active:

body.noscroll {
    overflow: hidden;
    position: fixed;
}

Answer №4

One problem that stands out is the incorrect event names being used for Bootstrap 3. Additionally, it appears that mobile browsers based on webkit do not follow the overflow: hidden CSS property when applied to the <body> element. A potential solution could be:

$(function(){
  $('#myModal').modal().on('shown.bs.modal', function(){
    $('body').css({
      position: 'fixed'
    });
  }).on('hidden.bs.modal', function(){
    $('body').css({
      position: ''
    });
  });
});

Answer №5

Not happy with the current solution as it doesn't work on my Note 8, causing the screen to freeze.

I've come up with a hack that may have some bugs, but it addresses the main problem :)

Check out the code on js bin

Feel free to ask for any clarifications!

Answer №6

After struggling with the same issue for a whole day, I finally found a solution!

Here's the code snippet that worked like a charm for me, hopefully, it does the same for you:

if( navigator.userAgent.match(/iPhone|iPad|iPod/i) ) {
        $('.modal').on('show.bs.modal', function() {
                    var scrollPosition=$(window).scrollTop();
                    $('.modal-open').css('position', 'fixed');
                  });
        $('.modal').on('hide.bs.modal', function() {
                    $('body').css('position', '');
                    $(window).scrollTop(scrollPosition);  
                  });
    }

Answer №7

Below is the HTML code for my modal:

<div class="modal fade" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true" tabindex="-1" aria-describedby="ContentLoader">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
            <h4 class="modal-title">Topic title</h4>
          </div>
          <div class="modal-body">
              <!-- some content -->
          </div>
          <div class="modal-footer">
              <!-- footer -->
          </div>
        </div>
      </div>
    </div>

Answer №8

After much thought, I have devised a top-notch solution. By implementing a prevent scroll feature when a dialog opens, and then re-enabling scroll when the dialog closes, we can effectively manage the scrolling behavior.

let previousScrollPosition = 0;
const preventScroll = function () {

    previousScrollPosition = $('body').scrollTop();
    $('body').css('overflow', 'hidden');
    $('body').css('position', 'fixed');

}
const enableScroll = function () {

    $('body').css('position', 'relative');
    $('body').css('overflow', 'auto');
    window.scrollTo(0, previousScrollPosition);

}

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

Utilizing slid.bs.carousel to retrieve values upon slide change

I am working on incorporating Bootstrap 4's Carousel with jQuery and PHP to create an odometer that dynamically changes its value on each slide. My plan is to utilize .addClass based on the length of the value. One challenge I am facing is that when ...

"Create a React Bootstrap Alert component with a dismissible button feature that is

I'm trying to add an "X" button to dismiss an alert on my website, but the bootstrap style isn't working properly. I've attempted setting the closeLabel to empty string, but it hasn't resolved the issue https://i.sstatic.net/YkDrY.png ...

The status value in the result has a whitespace just before the term "success"

Apologies for the unclear question, but I encountered a strange bug in my code. I am trying to show an alert to users informing them that the updates have been successfully completed. Below is the code snippet containing an if() block where the alert shoul ...

Ways to make video controls visible following the initial click on the video

I have a collection of videos on my website and I would like them to display with a poster (thumbnail image) initially. The video controls should only appear once the user clicks on the video for the first time. Therefore, when the page is loaded, the cont ...

The full execution of Jquery show() does not pause until it finishes

Here is the sequence I want to achieve: Show a div element with the CSS class yellow Execute a function for about 5 seconds Remove the yellow class and add the green CSS class "state Ok" However, when running my code, the div container does not appear u ...

Creating a Standard DIV Element (JavaScript Code)

Just a quick question here. http://jsfiddle.net/fkling/TpF24/ In this given example, I am looking to have < div>Bar 1</div> open as default... Any suggestions on achieving that? That would be all for now. Thank you so much! :D The JS script ...

Searching for a specific field within an array in a nested subdocument in MongoDB: What you need to know

I am having trouble retrieving lookup data for an embedded array within a document. Below is a snippet of the data: { "_id": "58a4fa0e24180825b05e14e9", "fullname": "Test User", "username": "testuser" "teamInfo": { "chal ...

Error: Using `[object HTMLDocument]` as a selector is not recognized in firefox

How can I load my local javascript library and execute an alert command? var jq = document.createElement('script'); jq.src = "http://127.0.0.1/js/jquery-3.3.1.min.js"; document.getElementsByTagName('head')[0].appendChild(jq); $(documen ...

Passing parameters from a Modal dialog to a Controller via Ajax

In my MVC3 project, I have a modal dialog that passes a parameter to the controller in this way: $("#SelectedCSIDivisionCodes").live("click", function () { var ID = $(this).val(); $.ajax({ type: "GET", url: '@ ...

Leveraging promises with node.js and couched/nano for asynchronous operations

Currently experimenting with the Q promises library in conjunction with couchDB and Nano. The code below is able to display messages in the console, however, it seems that the database is not being created as expected. var nano = require('nano') ...

Guide to customizing CSS styles within a div element using TypeScript code in a Leaflet legend

I'm struggling to add a legend to my map using Angular 5 and typescript. I need help with setting CSS styles for the values (grades) that are displayed on the legend. Can someone guide me on where to put the styles? TS: createLegend() { let lege ...

Is it better to process data in a React app using Express or handle it directly on the front end with React?

Hey there, I need some advice on how to create a league table for my application. The JSON data structure is set up like this: I'm considering whether to calculate each player's league data on the front-end using React by looping through the fixt ...

Discovering the initial element with a data attribute above zero using JQuery

I am working with a set of divs that have the class .item-wrap. At the moment, I am able to select the first div using this code snippet: $(".item-wrap:first").trigger( "click" ); Each .item-wrap element comes with a data-amount attribute. My challenge ...

Having issues with TableExport.js exporting Bootstrap HTML tables

I've been trying to use the TableExport.js plugin found at to add Bootstrap HTML table export functionality to my website. I meticulously followed all the steps to include jquery FileSaver, tableExport javascripts, and css. <!-- jQuery --> &l ...

Tips for connecting elements at the same index

.buttons, .weChangeColor { width: 50%; height: 100%; float: left; } .weChangeColor p { background: red; border: 1px solid; } .toggleColor { background: green; } <div class="buttons"> <p><a href="#">FirstLink</a></ ...

Ways to fix the issue of an unspecified user error in authjs

Having trouble with creating a web token using passport LocalStrategy and passport-jwt. I keep getting a user undefined error in auth.js ****401 Unauthorized**** (if (!user) { return res.json(401, { error: 'message' });}). How can I fix this issu ...

Masonry is experiencing compatibility issues with Bootstrap tabs

I have set up a bootstrap tab option and have also implemented masonry js. The issue I am facing is that the boxes appear differently in each tab; one appearing smaller and the other larger. The masonry layout seems to be working correctly in the first tab ...

Error encountered while attempting to display a view when pressing TouchableOpacity in a React Native application

Having trouble rendering a view when pressing on a TouchableOpacity in my React Native app. Any suggestions for a solution? import React, { Component } from 'react'; import { AppRegistry, View, TouchableOpacity } from 'react-nati ...

Ways to navigate by percentage in react

I'm working on a flexbox that scrolls horizontally with boxes set to 25% width. Currently, I have it scrolling by 420px which is causing responsive issues. Is there a way to implement the scroll using percentages instead of fixed pixel values in React ...

Is it possible to trigger an AJAX function automatically following the success of another AJAX function?

I am in the process of implementing a note system using procedural PHP and AJAX. This system should have the ability to display new notes without refreshing the page and load more notes dynamically without needing a full page refresh. Currently, each func ...