Unobtrusive JavaScript Print Link (with jQuery)
There are times when I have to implement designs that have print links on them. While I may think they are useless, I still have to make them work as they are a part of an approved comp. Sure, it is easy to have a link and then add an onclick event to launch the print window, but is that the right thing to do?
Clicking a JavaScript print link does nothing more than launch the browser’s print window. If a person has JavaScript disabled, nothing will happen when they click a link like this:
<a href="#" onclick="window.print(); return false;">Print</a>
Ideally, we do not want to have things on a page that do not work without JavaScript enabled. So the solution is to write the print link into the DOM using JavaScript, then attach a click event to the link. Luckily, I use jQuery on every project, so it makes the process much easier.
The Solution
In this example, we are going to prepend a list item with a link to an unordered list with the id of tools. Then, we attach a click event to the link we have just added to the DOM. Finally, we return false to override the action of the link.
Here is the script:
$(document).ready(function() {
$('ul#tools').prepend('<li class="print"><a href="#print">Click me to print</a></li>');
$('ul#tools li.print a').click(function() {
window.print();
return false;
});
});
Take a look at the demo page to see it in action. The script is nothing complex; it is just another example of using jQuery to improve a user’s experience.