Printing using JavaScript

December 09, 2011

I always thought it was very easy to add a JavaScript print page link to a page - all you had to do was add a simple line of code:

<a onclick="window.print()">Print this page</a>

All good, and the page prints. However, it turns out that this causes the page to reload, and if the page includes a form, and your user has started entering data, they’ll lose the data, and won’t be happy. A couple of things will prevent this. Here is a belt-and-braces version that won’t annoy the user by deleting their form data:

<a href="javascript:void(0)" onclick="window.print()">Print this page</a>