Sometimes, you’ll want to allow users the ability to print only a part of your page; for example, a table but not the various links around the page. It’s possible to use a printing stylesheet, but this can cause severe headaches when you need different parts printed at different times. Really, we want to be able to just say element.printElement(), and have it just work. That’s what the MooTools function below does. It’s loosely based around the concepts outlined at this website.
Element.implement({
printElement: function() {
var strName = 'printer-' + (new Date()).getTime(),
styles = $$('link[type=text/css]').clone(),
title = document.title,
that = this,
iframe = new IFrame({
name: strName,
styles: {
width: 1,
height: 1,
position: 'absolute',
left: -9999
},
events: {
load: function() {
var doc = this.contentDocument || window.frames[strName].document;
doc.title = title;
$(doc.body).adopt(styles, that.clone());
this.contentWindow.focus(); // IE requires us to focus before printing, or the parent prints.
this.contentWindow.print();
}
}
}).inject($(document.body));
iframe.dispose.delay(15000); // Destroy the iframe in 15s so that it doesn't hang around.
}
});