Scrolling background for a nested Bootstrap modal

I am facing an issue with a modal that has a lengthy content and a button to open another modal. Once the inner modal is closed, the outer modal becomes unresponsive. It fails to scroll and instead, the background starts to scroll.

While I have come across some similar questions on modal and scrolling like bootstrap modal inside a modal and Prevent BODY from scrolling when a modal is opened, my problem seems unique and not replicated in those discussions.

I have created a modified version on fiddle based on Bootstrap 3: prevent modal inside modal to trigger (hidden.bs.modal) every time to showcase this issue. When clicking on Cancel in the second modal, the first modal remains stuck.

code:

$('#btnUploadCancel').click(function() {
  $('#uploadImage').modal('toggle');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Open demo modal</button>
<p>
  Lorem ipsum .... long content
</p>
<div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h4 class="modal-title" id="myModalLabel">Demo Modal</h4>
      </div>
      <div class="modal-body">
        <p>
          <a href="#" data-toggle="modal" data-target="#uploadImage" class="btn btn-primary">Upload image</a>
        </p>
        Lorem ipsum ... long content
        <p>

        </p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
  <div class="modal" id="uploadImage" tabindex="-1" role="dialog" aria-labelledby="uploadImage-title" aria-hidden="true">
    <div class="modal-dialog modal-sm">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
          <h4 class="modal-title" id="uploadImage-title">Upload new image</h4>
        </div>
        <div class="modal-body">
          Testing Area
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" id="btnUploadCancel">Cancel</button>
          <button type="button" class="btn btn-success">Accept</button>
        </div>
      </div>
    </div>
  </div>
</div>

Answer №1

Make sure to update your Javascript code to keep the initial modal open as shown below -

    $('#btnUploadCancel').click(function () {
    $('#uploadImage').modal('toggle');

    $('body').addClass('modal-open');
});

Answer №2

$('.modal').on('show.bs.modal', function (event) {
        var idx = $('.modal:visible').length;
        $(this).css('z-index', 1040 + (10 * idx));
    });
    $('.modal').on('shown.bs.modal', function (event) {
        var idx = ($('.modal:visible').length) - 1; // adjust z-index after animation.
        $('.modal-backdrop').not('.stacked').css('z-index', 1039 + (10 * idx));
        $('.modal-backdrop').not('.stacked').addClass('stacked'); 
    });
   $('.modal').on('hide.bs.modal', function (event) { 
        var modal_length =  $('.modal:visible').length;
        if (modal_length>1)
        {
            $("body").css("overflow","hidden");
            $('.modal:visible').css("overflow-y","auto");
        }
    });

Answer №3

When the Bootstrap modal is shown, a new modal-open class is added to the body element. And when it is closed, the modal-open class is removed.

To ensure that the class is re-applied to the body element when closing a child modal, create a custom CSS class for the modals within the parent modal. In this example, the class used is .child-modal.

/* Add this class to the child modal when using a modal within a modal */
$(document).find('.child-modal').on('hidden.bs.modal', function () {
    console.log('hiding child modal');
    $('body').addClass('modal-open');
});

Here is the HTML code snippet:

<div class="modal fade" tabindex="-1" role="dialog">
     ...
     <a href="#" data-toggle="modal" data-target="#other_modal" title="Help">
       Open the other modal
     </a>
     ...
</div>
<div class="modal fade child-modal" id="other_modal" tabindex="-1" role="dialog">
   ... other codes here ...
</div>

Below is a working example with the necessary scripts and HTML:

$('#btnUploadCancel').click(function() {
  $('#uploadImage').modal('toggle');
});


$(document).find('.child-modal').on('hidden.bs.modal', function () {
    console.log('hiding child modal');
    $('body').addClass('modal-open');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Open demo modal</button>
<p>
  Lorem ipsum .... long content
</p>
<div class="modal" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h4 class="modal-title" id="myModalLabel">Demo Modal</h4>
      </div>
      <div class="modal-body">
        <p>
          <a href="#" data-toggle="modal" data-target="#uploadImage" class="btn btn-primary">Upload image</a>
        </p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliq......
</div>

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

Angular does not automatically update the template

I've been grappling with this issue for quite some time now and I can't seem to figure out why the angular template is failing to refresh when the scope changes. Here's a link to my JSFiddle - http://jsfiddle.net/HB7LU/2591/ (please note tha ...

Individual Ajax data

Starting out with javascript, I'm a bit unsure of how to tackle this task. Essentially, I am looking to implement a for loop within the ajax data call, rather than listing each item manually. jQuery(document).ready(function() { ...

Deciphering HTML encoding for text fields

As I transition from the Microsoft stack, specifically WPF, to HTML5, I apologize for any beginner-level questions. Today's topic is HTML encoding and decoding. Imagine an HTML5 application making AJAX calls to a C# backend using HTTP. The server al ...

Customize the daterangepicker to exclusively display the option for "Select Date Range"

Recently, I came across the daterangepicker plugin and I am attempting to personalize it. The link to the plugin is Is there a way to remove options like "Last 7 days", "Month to date", "Year to date", etc.? Ideally, I only want to display the "Date range ...

What causes the border to trigger the appearance of a scrollbar due to an overflow?

The first image display a scrollbar, while the second one does not. It all comes down to the .tabulator CSS class and specifically the border property. How come only a 1px border impacts the scroll feature instead of affecting the entire content? https: ...

How to Convert Pixel Units to Rem and Em in CSS?

Until recently, I developed my website exclusively using pixels, which has made it less responsive than I'd like. Is there a method to efficiently convert pixel measurements to rem/em units, allowing for quicker and easier modifications? ...

How to use jQuery to adjust the opacity of a CSS background

I am facing a challenge with changing the transparency of a <div> element's background color using jQuery. An external API provides me with a hexadecimal value for the color: #abcdef I make use of jQuery (version 1.9) to apply this color using ...

What is the method to retrieve data in Vue when utilizing arrow functions?

When utilizing Vue and arrow functions in methods, we encounter the issue that arrow functions do not have a this keyword. The question then arises of how to access data properties such as list or object. export default { data() { return { list ...

Role Based Routing in React allows for different paths and components

I am currently working on a project involving React and I need to implement different routes for admin and driver roles. I have two separate route objects for each role's claims. I am retrieving the user's role from an API and I want to display t ...

Simple Way to Modify Color of Active Page Link - HTML, CSS, and JavaScript

I found a helpful example on how to change link colors for the current page here. Here is the script I added: <script> // current page highlight $(document).ready(function() { $("[href]").each(function() { if (this.href == window.l ...

Changing the Size of X-Axis Labels Font in a Line Chart Using ChartJS

Struggling with adjusting the font size of x-axis labels in my line chart design using ChartJS. I've attempted to set the x-axis ticks to my desired size, but the font size remains unchanged: options:{ scales:{ xAxis: [{ ...

Refresh your HTML by reloading the JavaScript source

In my Ubuntu setup, I've been using chart.js to generate a graph displaying the values from a pressure sensor on an HTML document. Most of the project is complete, but I've encountered a challenge for which I haven't found a satisfactory sol ...

managing json arrays within Laravel

I am currently working on a project where I am focusing on creating an ajax call and handling the data that comes back. Here is what my Ajax call looks like: $.ajax({ type: 'GET', dataType: "json", url: ****, ...

Toggling multiple sets of checkboxes using Jquery

Currently, everything is functioning as expected, but there seems to be a minor issue... In my setup, I have 2 sets of checkbox blocks labeled Group A and Group B If I choose 'all' for Group A, all checkboxes in that group toggle their state ac ...

"Upon refreshing, the background image reverts back to its original default setting

With React, I have implemented a feature where users can navigate to their 'settings' page and select an image to set as their background. I used DOM manipulation to achieve this functionality successfully! However, whenever the page is refreshed ...

PHP/AJAX user action history manager

Is there a library available that offers undo/redo functionality with a complete history for a web application? One possible solution could be a system using php/javascript/ajax where you can record the opposite action and variable state for each user acti ...

Adding AngularJS data to JSON file for update

I'm feeling lost on where to begin with this. I am working with an AngularJS form and I need it to add the data it sends to a json file. I understand that AngularJS is client-side, so my main issue lies in figuring out how to manage the data being sen ...

Tips on successfully transferring row data that has been clicked or selected from one adjacent table to another table

Currently, I am facing a challenge with two tables that are positioned next to each other. My goal is to append a selected row from the first table to the second table. After successfully extracting data from the selected row and converting it into an arr ...

Is it possible to leverage the flex features of react-native in a manner similar to the row/column system of

Is it a good idea to utilize flex in react native by creating custom components that retrieve flex values? I previously used the bootstrap grid system and now I am exploring react native. Is there a way to implement this example using react-native bootstr ...

Observing a peculiar discrepancy in how various versions of JSON.stringify are implemented

Imagine having a deeply nested JS object like the example below that needs to be JSON-encoded: var foo = { "totA": -1, "totB": -1, "totC": "13,052.00", "totHours": 154, "groups": [ {"id": 1, "name": "Name A", " ...