You can get the HTML content of that section from the innerHTML property. Step 4: Add the section you want to print to the body of this new window. Because this window won't have any style by default. You also have to link an external CSS stylesheet using the link tag. Therefore, you need to write an HTML markup for this printWindow window using the () method.įirst, add different HTML tags like html, head, title, body etc. Step 3: As you already know, it will open a black window. Create a new window with only the section to printĬonst printWindow = window.open('', 'Print Window') The printWindow variable now holds a reference to this new window. The second parameter of this method sets the name of the new window to " Print Window". I am not specifying any URL, so it will open a blank page. Step 2: Inside the event callback function, open a new browser window by calling the window.open() method. Select and print a section of a webpage here const btn = document.getElementById('btn')Ĭonst sectionToPrint = document.getElementById('section-to-print') I am also selecting the section that I want to print and store in the sectionToPrint variable. Step 1: I am selecting the button element that will trigger the click event. But don't worry I will explain each step in detail so that you understand the process. Printing a specific section of a page is a little complex. You can get it using this window.print() method. Often we want to print part of a page using JavaScript. So far you have seen the technique to print a full page. It will open a print dialog box, allowing you to select appropriate options for printing the current document.Īlso Read: Mastering JavaScript Media Queries For Responsive Web Design How to Print a Specific Part of a Web Page in JavaScript If you click this button, it will execute the callback function which calls the window.print() method. Here, I am listening to the click event on this button. Window.print() // Print the entire webpage const btn = document.getElementById('btn') For that, you need to set up a click event listener on this HTML button element. It will print the page whenever I click this button. This method is available in all modern browsers and is specifically designed to print the current window's contents. All you need to do is call the print() method on the window object. Printing an entire webpage using JavaScript is a straightforward process. How to Print Entire HTML Web Page Using JavaScript This method opens a print dialog box where users can select different options to generate a printed copy of the content easily. Printing a web page or a specific part of a web page can be accomplished by calling the window.print() method in JavaScript.
0 Comments
Leave a Reply. |