Monday, May 27, 2013

Unobtrusive JavaScript

<p id="printthis">Thank you for your order. Please print this page for your records.</p> <script type="text/javascript"> (function(){ if(document.getElementById){ var pt = document.getElementById('printthis'); if(pt && typeof window.print === 'function'){ var but = document.createElement('input'); but.setAttribute('type','button'); but.setAttribute('value','Print this now'); but.onclick = function(){ window.print(); }; pt.appendChild(but); } } })(); </script>

  • By wrapping the whole functionality in an anonymous function and immediately executing it — this is what(function(){})() does — we don’t leave any global variables behind.
  • We test for DOM support and try to get the element we want to add the button to.
  • We then test if the element exists and if the browser has a window object and a print method (by testing if the type of this property is function).
  • If both are true, we create a new click button and apply window.print() as the click event handler.
  • The last step is to add the button to the paragraph.

No comments:

Post a Comment