Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How can I pop-up a print dialog box using JavaScript?
To pop-up a print dialog box using JavaScript, use the window.print() method. This method opens the browser's print dialog, allowing users to select printing options like printer choice, page range, and paper size.
Syntax
window.print();
Basic Example
Here's a simple example that opens the print dialog when a button is clicked:
<!DOCTYPE html>
<html>
<head>
<title>Print Dialog Example</title>
</head>
<body>
<h1>My Document</h1>
<p>This content will be printed when you click the print button.</p>
<button onclick="openPrintDialog()">Print Page</button>
<script>
function openPrintDialog() {
window.print();
}
</script>
</body>
</html>
Print Specific Content
You can also print only specific sections of a page by modifying the content temporarily:
<!DOCTYPE html>
<html>
<head>
<title>Print Specific Content</title>
</head>
<body>
<div id="header">Website Header</div>
<div id="printable-content">
<h2>Report Title</h2>
<p>This is the content that will be printed.</p>
</div>
<div id="footer">Website Footer</div>
<button onclick="printSpecificContent()">Print Report Only</button>
<script>
function printSpecificContent() {
let printContent = document.getElementById('printable-content').innerHTML;
let originalContent = document.body.innerHTML;
document.body.innerHTML = printContent;
window.print();
document.body.innerHTML = originalContent;
}
</script>
</body>
</html>
Using CSS for Print Styling
You can control how content appears when printed using CSS media queries:
<!DOCTYPE html>
<html>
<head>
<title>Print with Custom CSS</title>
<style>
.no-print {
display: block;
}
@media print {
.no-print {
display: none;
}
body {
font-size: 12pt;
color: black;
}
}
</style>
</head>
<body>
<h1>Document Title</h1>
<p>This content will be printed.</p>
<div class="no-print">
<button onclick="window.print()">Print Document</button>
<p>This section won't appear in print.</p>
</div>
</body>
</html>
Key Points
-
window.print()opens the browser's native print dialog - The method doesn't return any value and executes immediately
- Users can cancel the print operation from the dialog
- Use CSS
@media printrules to customize print appearance - The
.no-printclass is commonly used to hide elements during printing
Browser Compatibility
The window.print() method is supported in all modern browsers including Chrome, Firefox, Safari, and Edge. It works consistently across different platforms.
Conclusion
The window.print() method provides a simple way to open the print dialog in JavaScript. Combine it with CSS media queries for better control over printed content appearance.
