Last updated on November 8th, 2024 at 01:13 pm
The JavaScript code in the example enables users to print a specific part of a webpage rather than the entire page. Here’s a breakdown of how it works:
<script>
function Print_Div() {
var prtContent = document.getElementById('main');
var WinOpen = window.open('', '', 'width=800,height=650,scrollbars=1,menuBar=1');
var page = prtContent.innerHTML;
WinOpen.document.write(page);
WinOpen.document.close();
WinOpen.focus();
WinOpen.print();
}
</script>
<body>
Outside Main <P>
<button onclick="Print_Div()">Print</button>
<div id="main">
Testing Main Printing, Only this area of the webpage will get printed.
</div>
</body>
Explanation
- Function Definition:
- The function
Print_Div()
is defined to handle the printing action when called.
- The function
- Selecting Content to Print:
var prtContent = document.getElementById('main');
finds the HTML element with theid="main"
and assigns it toprtContent
. This element will be the only part of the page that gets printed.
- Opening a New Window:
var WinOpen = window.open('', '', 'width=800,height=650,scrollbars=1,menuBar=1');
opens a new window with specific dimensions (800×650) and settings like scrollbars and menu bar.
- Writing Content to the New Window:
var page = prtContent.innerHTML;
stores the HTML inside themain
div inpage
.WinOpen.document.write(page);
writes this content to the newly opened window.
- Finalizing the New Window:
WinOpen.document.close();
completes the document structure in the new window.WinOpen.focus();
brings the new window to the front, so it’s the active window.
- Printing the Content:
WinOpen.print();
opens the print dialog for the new window, allowing the user to print only the selectedmain
div content.
HTML Structure
The button element <button onclick="Print_Div()">Print</button>
calls the Print_Div()
function when clicked. The content inside the <div id="main">...</div>
section will be displayed in the new window for printing.
Only the text inside the <div id="main">
will be displayed in the print dialog, while anything outside this div, like “Outside Main,” will be ignored. This approach is useful for isolating specific content for printing.