Skip to content

Instantly share code, notes, and snippets.

@corymartin
Last active December 11, 2015 23:38
Show Gist options
  • Save corymartin/4677909 to your computer and use it in GitHub Desktop.
Save corymartin/4677909 to your computer and use it in GitHub Desktop.
Prints an element and its contents. jQuery free version of Ben Nadel's jQuery plugin. http://www.bennadel.com/blog/1591-Ask-Ben-Print-Part-Of-A-Web-Page-With-jQuery.htm
/**
* Prints an element and its contents.
* jQuery free version of Ben Nadel's jQuery plugin.
* http://www.bennadel.com/blog/1591-Ask-Ben-Print-Part-Of-A-Web-Page-With-jQuery.htm
*
* @param {HTMLElement} el
* @returns {undefined}
*/
function printElement(el) {
var csslinks = document.getElementsByTagName('link');
var css = '';
for (var link, i = 0; i < csslinks.length; i++) {
link = csslinks[i];
if (link.rel !== 'stylesheet') continue;
css += link.outerHTML;
}
var html = [
'<html>'
, '<head>'
, '<title>' + document.title + '</title>'
, css
, '</head>'
, '<body>'
, el.outerHTML
, '</body>'
, '</html>'
].join('');
var iframe = document.createElement('iframe');
iframe.name = 'printElement-' + (new Date).getTime();
iframe.style.width = '1px';
iframe.style.height = '1px';
iframe.style.position = 'absolute';
iframe.style.left = '-9999px';
document.body.appendChild(iframe);
var doc = iframe.contentWindow.document;
doc.open();
doc.write(html);
doc.close();
doc.body.focus();
iframe.contentWindow.print();
setTimeout(function() {
if (iframe) document.body.removeChild(iframe);
}, 60 * 1000);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment