Chrome browser exhibits a phenomenon where the Bootstrap modal will erroneously print the same page multiple times based on the

When I open a modal, there's a print button inside it. I've researched solutions provided here and here to enable printing of Bootstrap modals, but I'm encountering a Chrome-specific bug. The issue doesn't occur in Safari, Firefox, or Edge.

Upon trying to print only the modal contents, the same page is printed multiple times, correlating with the number of pages when printing the body.

For a clearer understanding, please visit my fiddle to see the problem in action. Clicking the print button will result in the modal contents printing multiple times due to the background body being equated to numerous print pages.

The culprit seems to be the property

body.modal-open { visibility: hidden; }
, whereby visibility: hidden; still reserves page space. Changing it to
body.modal-open { display: none; }
hides all modal content, rendering a blank page upon printing.

CSS code:

@media print {
  body.modal-open {
    visibility: hidden;
  }

  body.modal-open .modal .modal-header,
  body.modal-open .modal .modal-body {
    visibility: visible;
  }

   .close, #printBtn {
     display: none;
   }
}

HTML code: Launch demo modal

<div class="modal-must-live-inside-of-this-body-content">
<!-- Modal -->
<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">
        <button id="printBtn">
            Print this modal
        </button>
        <br /><br />
        Note: This should *ONLY* Print the contents (title, body, etc) of the modal when you click the "Print this modal" button. Which it does, however since the background body content is 12 pages worth of text it prints this same modal 12 times...
        <br /><br />
        I believe this is due to the fact that the background body has the `visibility: hidden` instead of `display: none`.
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut porttitor congue nisl non tristique. Sed cursus velit non erat finibus molestie. Cras porttitor leo et tristique placerat. Nunc non nisi nec erat vestibulum aliquam sed in mauris. Aliquam erat volutpat. Nulla malesuada enim a tellus luctus commodo. Phasellus porttitor pharetra tellus sit amet accumsan. Nam fringilla leo sit amet tellus eleifend, eu imperdiet eros semper. Ut tristique tempus ligula sed bibendum.

Quisque eu porttitor lacus, et placerat sapien. Curabitur venenatis nec velit quis pulvinar. Nulla vel fermentum sapien, sed hendrerit sapien. Praesent in condimentum leo, nec lobortis elit. Curabitur maximus eros risus, quis luctus augue efficitur in. Nulla iaculis velit felis. Sed sit amet consectetur libero, non laoreet ipsum. Aenean nec elit id leo gravida eleifend. Mauris id sem egestas, vulputate ipsum ut, consequat justo. Mauris malesuada condimentum arcu. Nulla dictum eu nunc id tincidunt. Nulla facilisi. Sed eget purus ac sapien elementum porta. Integer a laoreet ex. Aliquam eu erat pharetra, aliquam turpis non, lacinia libero. Etiam et nisi quis ipsum pharetra egestas.

Nunc hendrerit lacus justo, tempus dignissim quam elementum id. Nullam et volutpat sapien. Ut a cursus ex. Sed magna neque, congue vel massa feugiat, porta iaculis nibh. Maecenas ac consectetur libero. Maecenas tristique posuere libero, sed fermentum neque tristique ac. Sed hendrerit id velit ac sollicitudin. Vivamus gravida sapien in lobortis commodo. Sed sagittis, turpis et mattis lobortis, erat eros rhoncus velit, nec fringilla eros ante interdum nunc.

Nunc cursus finibus egestas. Sed sit amet velit metus. Fusce quis condimentum arcu, a ultricies augue. Vivamus blandit purus eu ex viverra ullamcorper. In sed erat in augue tincidunt euismod. In eget lobortis nunc. Vestibulum non arcu et leo sagittis finibus. Duis pulvinar tellus eget diam dictum pellentesque. Nulla nec mauris metus. Praesent lacinia ipsum scelerisque purus auctor tincidunt. Nam sagittis massa sit amet nisi condimentum, ut dignissim ligula rutrum. Suspendisse accumsan, arcu eu maximus dignissim, purus elit vulputate ante, id rutrum tellus nisi blandit dolor. Proin a lorem vel libero maximus pharetra et a felis. Donec venenatis fermentum lacus non vestibulum.
</div>

Answer №1

Your fiddle may not perfectly reflect your actual issue, but you can solve the problem by adding a class to the body content and setting it to display: none; in the print scenario. This will prevent unnecessary paging. Check out this example here: http://jsfiddle.net/nr5kzhxv/

body.modal-open .body-content {
    display: none;
  }

Update: It seems that the original fiddle now displays the modal within the content element, so this solution may not work without restructuring. The best approach would be to restructure the DOM upfront, but you may also be able to make changes at runtime when the modal display is triggered by a button or event.

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

What is the reason why createServer() is often not recognized as a function?

After installing express globally and npm on my express app, I am encountering issues with both intellisence and the app itself (I am using visual studio code on mac OS Yosemite). Below is a snippet of the code: /// <reference path="typings/node/node. ...

The latest update of NextJS, version 13.1.4, encounters issues when implementing SCSS support with the error message "Module next/dist/compiled/sass-loader/fibers.js not

After setting up a new NextJS project, I decided to incorporate SCSS support. The guidelines provided in the documentation seemed straightforward. Following the installation instructions and including an import of SCSS as shown below: import "@/styles ...

The CSS property input::-webkit-outer-spin-button adjusts the margin-left and is exclusively visible in Chrome browser

Strange things are happening... Let me share the code for my inputs: #sign_in input#submit { height: 56px; background-color: #88b805; font-weight: bold; text-decoration: none; padding: 5px 40px 5px 40px; /* top, right, bottom, left ...

What is the best way to implement a new search input for my datatable while also enabling the searchHighlight feature?

I'm attempting to implement a search bar for my datatables. I need to hide the default search engine that comes with datatables, so I added a script that I found in a forum. However, when I try to run it in my code, it doesn't work and displays a ...

What is the process for adding elements to the parent elements that have been selected using getElementsByClassName?

Here is the JSP code snippet I'm working with: <% while(resultSet1.next()){ out.println("<p class='comm'>"); out.println(resultSet1.getString("answer_content")); ...

Tips for positioning footer text to the left and right, similar to Google's style

Explore www.google.com for inspiration. You will notice a footer containing links to Advertising, Business, and About on the left side, and Privacy, Settings, Terms, etc. on the right side at the bottom of the page. I am an aspiring developer attempting ...

Enabling draggable behavior for div elements on Mozilla Firefox

I've attempted the code mentioned in this forum but unfortunately, it's not working for me. I am currently using Firefox 15 and it seems to work fine in Chrome. Below is my code : <!DOCTYPE html> <head> <title>A Simple Dragg ...

Python on the server side generating a downloadable zip file

After passing a parameter from my client to a python script on the server through a GET request, the script initiates a process that results in the creation of a zip file. However, upon making an AJAX call in my client-side JavaScript, I am only able to co ...

Display <div> exclusively when in @media print mode or when the user presses Ctrl+P

Looking for a way to create an HTML division using the div element that is only visible when the print function is used (Ctrl+P) and not visible in the regular page view. Unfortunately, I attempted the following method without success. Any advice or solut ...

How can I simulate keyboard events in Angular using a button click?

I've included separate buttons for Ctrl+z and Ctrl+y functionalities. When these buttons are clicked, I want them to perform the respective undo and redo actions programmatically. Below is the code snippet for this functionality. undoText(event:MouseE ...

What is the reason behind getElementsByClassName not functioning while getElementById is working perfectly?

The initial code snippet is not functioning correctly DN.onkeyup = DN.onkeypress = function(){ var div = document.getElementById("DN").value document.document.getElementsByClassName("options-parameters-input").style.fontSize = div; } #one{ heigh ...

Bootstrap 3 offset doesn't respond to dimensions

Even though I have set an offset for a medium-sized screen, the offset still appears in large screens. Here is a snippet of my HTML code. How can I resolve this issue? <div class="col-lg-6 col-sm-12"> <div class="row"> <div class="co ...

Applying a CSS class to a newly generated row with JavaScript

I have a JSP page where I dynamically add rows to a table using a different Javascript function than in my previous query. While I can add elements to the table columns, I'm unable to apply a style class that is defined in a CSS file. Here is my Java ...

Finding the absolute root path of a npm package in Node.js

Objective I am on a quest to find a reliable method to ascertain the absolute root path of an npm package that has been installed in Node.js. Challenge Although I am aware of require.resolve, it only provides the entry point (path to the main module) an ...

Retrieve the present value from a Selectpicker using jQuery within the Codeigniter Framework

I attempted to use DOM manipulation to retrieve the value of the currently selected option from the selectpicker. My goal was to have the value of the selectpicker id="service_provider_select" printed first. However, whenever I changed the option using the ...

retrieve undefined value from redux state in a React Native application

Received the data in reducer but encountering issues accessing it in the component. Below is the connection code: const mapStateToProps =state => { return { name:state.fbLogin.name } } function mapDispatchToProps(dispatch){ ...

What is the best way to retrieve a previously used jQuery function?

The dynamic table I've created has the functionality to search, display search results in pagination, and auto-compute fields. This is how it works: Users search for their items in the search box If the search results are extensive, the system displ ...

Express server continuously returning 404 error for all requests originating from the index page

Experiencing a challenge with the express/gulpfile.js code. Express can serve the index.html without issue, but it fails to navigate to the lib/* directory resulting in all requests for resources at the top of my index.html returning 404 errors. Browser-s ...

After a CSS animation, the Div element disappears from view

I recently implemented a CSS3 delayed animation on page load. Everything was working smoothly until I noticed that after the animation finishes, the DIV reverts back to visibility: hidden. .content-left { margin-left: 100px; margin-top: 32px; ...

What is the best way to display all divs once more after all filter-checkboxes have been unchecked?

I created a custom filter that displays board games based on the number of players and playing time selected through checkboxes. Initially, the filter works as intended when first loaded and used. However, I encountered an issue where if all checkboxes are ...