How to Print Specific HTML Content on Button Click Without Printing the Entire Page?

Susan Sarandon
Release: 2024-10-26 17:25:30
Original
815 people have browsed it

How to Print Specific HTML Content on Button Click Without Printing the Entire Page?

Printing Specific HTML Content on Button Click Without Including Full Webpage

Printing only specific HTML content upon a user's button click can be achieved in various ways. One method is to create a hidden div element to hold the desired HTML. This div should have its display property set to 'print' for printing purposes, while its display value remains 'none' for screen display. Other elements on the page can have their display properties adjusted to show on screen but hide during printing. This method, however, requires meticulous management of all page elements' display properties.

An alternative approach is to create a new, isolated webpage containing solely the HTML content to be printed. This new page can be dynamically loaded into a hidden iframe when the user clicks the print button. Once the iframe has fully loaded, the browser's print function can be triggered, and the embedded HTML will be printed without any unwanted page elements. This method offers greater flexibility and dynamic control over the printing process.

Here's an example using the second approach:

<code class="javascript">// Create an invisible iframe to hold the print-only HTML
const printFrame = document.createElement('iframe');
printFrame.style.display = 'none';
document.body.appendChild(printFrame);

// Dynamically load the print-only HTML into the iframe
printFrame.onload = function() {
  // Trigger the browser's print function once the print-only page is loaded
  window.print();
}
printFrame.src = 'print-only.html';</code>
Copy after login

This solution allows you to print specific HTML content conveniently upon button click without modifying the main webpage's appearance or content. It ensures that only the intended HTML is printed, providing a more user-friendly printing experience.

The above is the detailed content of How to Print Specific HTML Content on Button Click Without Printing the Entire Page?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!