{"authorId":"1","title":"Unobtrusive JavaScript Print Link (with jQuery)","slug":"unobtrusive-javascript-print-link-with-jquery","postDate":1228897806,"expiryDate":null,"enabled":"1","fields":{"2":"<p>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?<\/p>\n<!--more-->\n<p>Clicking a JavaScript print link does nothing more than launch the browser&rsquo;s print window. If a person has JavaScript disabled, nothing will happen when they click a link like this:<\/p>\n<div class=\"codeblock\"><code>\n&lt;a&nbsp;href=\"#\"&nbsp;onclick=\"window.print();&nbsp;return&nbsp;false;\"&gt;Print&lt;\/a&gt;&nbsp;\n\n<\/code><\/div>\n\n<p>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.<\/p>\n\n<h2>The Solution<\/h2>\n<p>In this example, we are going to prepend a list item with a link to an unordered list with the id of <strong>tools<\/strong>. Then, we attach a click event to the link we have just added to the DOM. Finally, we <strong>return false<\/strong> to override the action of the link.<\/p>\n\n<p><strong>Here is the script:<\/strong><\/p>\n<div class=\"codeblock\"><code>\n$(document).ready(function()&nbsp;&#123;<br \/>&nbsp;$('ul#tools').prepend('&lt;li&nbsp;class=\"print\"&gt;&lt;a&nbsp;href=\"#print\"&gt;Click&nbsp;me&nbsp;to&nbsp;print&lt;\/a&gt;&lt;\/li&gt;');<br \/>&nbsp;$('ul#tools&nbsp;li.print&nbsp;a').click(function()&nbsp;&#123;<br \/>&nbsp;&nbsp;window.print();<br \/>&nbsp;&nbsp;return&nbsp;false;<br \/>&nbsp;&#125;);<br \/>&#125;);&nbsp;\n\n<\/code><\/div>\n\n<p>Take a look at the <a href=\"http:\/\/trevordavis.net\/play\/javascript-print-link\/\">demo page<\/a> to see it in action. The script is nothing complex; it is just another example of using jQuery to improve a user&rsquo;s experience.<\/p>","14":{"old_id":{}}}}