Click To Print

Here’s a nifty little piece of javascript I whipped up the other day in response to a client request.

With this code (and jquery) on a web page an element on a web page with the “clicktoprint” class becomes clickable. When clicked, it is printed, but only that element. In addition, the element will be scaled to the full width of the page.

I was asked to do this so that a client could have a voucher on their website which you could click on and have it printed. Their previous solution (using a ‘print’ media query in the site css) meant that the rest of the page could never be printed. This code injects a new piece of css for the duration of the special print and removes it afterwards, allowing the rest of the page to be printed by the regular means.

<script type="text/javascript">
jQuery(document).ready(function() {
	jQuery('.clicktoprint').click(function() {
		jQuery(this).parents().each(function(idx,i) {
			jQuery(i).addClass('clicktoprint-parent');
		});
		jQuery('head').append('<style id="clicktoprint-style">@media print { * { display: none; } .clicktoprint, .clicktoprint-parent {display: block !important; width: 100% !important;} }</style>');
		window.print();
		jQuery('style#clicktoprint-style').remove();
		return false;
	});
});
</script>

Leave a Reply