Empowering Today’s Learners to Become Tomorrow’s Leaders
Next we will create a print button with Javascript. This button sends you to a print page so that you can print a document. We do this through the print() function in Javascript. The print() function in javascript is a function which prints the content of a page. One approach is to setup your webpage so that the "print" button will only print the content that you put within a "<div>" tag.
Step 1 - Put this Javascript in your webpage:
// Print Div Area
function printDiv() {
var printContents = document.getElementById("printArea").innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
Step 2 - Put a div tag around part of your webpage with an ID:
<div id=printArea>
<h1>Welcome to My Web Page!</h1>
<p>This is my first Web page.</p>
<p>Isn't it cool!</p>
<p>Today is: <strong id="date"></strong> </p>
<p> Count down until Thanksgiving Break: <br>
<span id="days"></span>
<span id="hours"></span>
<span id="mins"></span>
<span id="secs"></span>
<h2 id="end"></h2>
</p>
</div>
Step 3 - Put a button inside your div tag so a user can print the div tag area.
<p>🖨️ <input type="button" value="Print This Only" onclick="printDiv();"/></p>