The JavaScript Window print() method is used to open the browser’s print dialog and print the current document. It does not take any arguments and does not return a value.
Here are some examples of how the print() method can be used in JavaScript code:
- To open the browser’s print dialog and print the current document, you can use the following code:
window.print();
- To open the browser’s print dialog and print a specific element on the page, you can use the following code:
// get the element to print
var element = document.getElementById('myElement');
// create a new window with the element
var win = window.open('', '', 'width=800,height=600');
win.document.body.appendChild(element);
// open the print dialog and print the element
win.print();
- To open the browser’s print dialog and print the current page with a specific CSS stylesheet, you can use the following code:
// create a new window with the current page
var win = window.open(location.href, '', 'width=800,height=600');
// add a link to the CSS stylesheet
var link = win.document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'mystyles.css';
win.document.head.appendChild(link);
// open the print dialog and print the page
win.print();
Overall, the print() method provides a convenient way to open the browser’s print dialog and print the current document or specific elements on the page. It can be used in combination with other techniques, such as creating new windows or adding CSS styles, to customize the printed output.
Leave a Reply