There are times when you may need to print a specific portion of your webpage, such as a user receipt or a summary of some sort. In this blog post, we’ll learn how to print a specific div element using jQuery.
Step 1: Include jQuery Library
First, make sure you have included the jQuery library in your project. You can download it from the official jQuery website or include it directly from a Content Delivery Network (CDN), like Google:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Step 2: Add a Print Button
Add a button to your HTML that will trigger the print functionality:
<button id="printBtn">Print Div</button>
Step 3: Create the Div You Want to Print
Create a div element in your HTML with the content you want to print. Give it an ID so that you can easily target it using jQuery:
<div id="printDiv"> <h2>Summary</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio.</p> </div>
Step 4: Write the jQuery Code to Print the Div
Now it’s time to write the jQuery code that will be triggered by the print button. When the button is clicked, the following steps will take place:
- Clone the div element we want to print
- Create a new window or iframe to host the content
- Append the cloned div to the new window or iframe
- Call the print function on the new window or iframe
- Close the new window or remove the iframe after printing is complete
Here’s the jQuery code to achieve this:
$(document).ready(function() { $("#printBtn").on("click", function() { var printContents = $("#printDiv").clone(); var printWindow = window.open("", "_blank"); printWindow.document.write("<title>Print Div</title>"); printWindow.document.write(printContents.html()); printWindow.document.write(""); printWindow.document.close(); printWindow.print(); setTimeout(function() { printWindow.close(); }, 100); }); });
And that’s it! With this simple jQuery code, you can now print a specific div element on your webpage. This can be very useful for printing only the relevant content instead of the entire page. Just remember to include the jQuery library, create a print button, and target the div you want to print.