Sometimes when creating a web page, we may want to add a functionality to print not the whole page, but just some part of it like for example all the information contained in a particular DIV element.
In the example below, we'll create a div element with some content and a JavaScript function that will print the content of this div when a link is clicked.
Let's start with adding a div and specify some ID for it and add some test content.
<div id="data_container">
Some test content goes here ...
</div>
Then we'll create a JavaScript function div_print() that will get the content of this div element, open a new browser window, assing this html content to it and then call the JavaScript native window print function to print the content
<script>
function div_print()
{
var contents = $("#data_container").html();
var frame1 = $('<iframe />');
frame1[0].name = "frame1";
frame1.css({ "position": "absolute", "top": "-1000000px" });
$("body").append(frame1);
var frameDoc = frame1[0].contentWindow ? frame1[0].contentWindow : frame1[0].contentDocument.document ? frame1[0].contentDocument.document : frame1[0].contentDocument;
frameDoc.document.open();
frameDoc.document.write(contents);
frameDoc.document.close();
setTimeout(function ()
{
window.frames["frame1"].focus();
window.frames["frame1"].print();
frame1.remove();
}, 500);
}
</script>
Finally to be able to test this function, we'll create a simple test link -
<a href="javascript:print_div()">Print it</a>