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

  1. Function Definition:
    • The function Print_Div() is defined to handle the printing action when called.
  2. Selecting Content to Print:
    • var prtContent = document.getElementById('main'); finds the HTML element with the id="main" and assigns it to prtContent. This element will be the only part of the page that gets printed.
  3. 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.
  4. Writing Content to the New Window:
    • var page = prtContent.innerHTML; stores the HTML inside the main div in page.
    • WinOpen.document.write(page); writes this content to the newly opened window.
  5. 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.
  6. Printing the Content:
    • WinOpen.print(); opens the print dialog for the new window, allowing the user to print only the selected main 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.