HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

jQuery plugin which will print to a printer an element or a jQueryUI Dialog

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
pluginwilljqueryprintprinterelementwhichdialogjqueryui

Problem

I have a need to print the content of a jQueryUI Dialog to a printer, and I couldn't find anything to my liking. I developed the following simple jQuery plugin which prints one or more provided HTML elements, and am using it to print the jQueryUI Dialog DIV element. The code is below, and a live example is located here.

It works on FF 26.0. However, after printing a couple of times, FF asks the user if popups should be disabled, which I wish not to happen. Also, it doesn't work with older IE, and likely other browsers. Don't worry because, when printing, you still need to click the operating system print dialog, so you won't waste any paper!

Please provide any recommendations on how this plugin could be improved.

Actual Plugin:

```
/*
* jQuery printIt
* Print's the selected elements to the printer
* Copyright Michael Reed, 2014
* Dual licensed under the MIT and GPL licenses.
*/
(function($){
var defaults = {
elems :null, //Element to print HTML
copy_css :false,//Copy CSS from original element
external_css :null //New external css file to apply
};

var methods = {
init : function (options) {
var settings = $.extend({}, defaults, options)
elems=$(settings.elems);
return this.each(function () {
$(this).click(function(e) {
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
$(iframe).load(function(){
elems.each(function(){
iframe.contentWindow.document.body.appendChild(this.cloneNode(true));
});
if(settings.copy_css) {
var arrStyleSheets = document.getElementsByTagName("link");
for (var i = 0; i < arrStyleSheets.length; i++){
iframe.contentWindow.document.head.appendChild

Solution

From a once over:

  • I am not a native English speaker but //Element to print HTML confused me. Maybe //HTML elements to be printed?



  • delete settings; is meaningless in destroy ( see comment )



  • elems=$(settings.elems); should be var elems = $(settings.elems); otherwise you pollute the global namespace



  • You declare var i twice in a for loop



  • You should consider removing the iframe in destroy



All in all very clean, maintainable code.

Context

StackExchange Code Review Q#39235, answer score: 2

Revisions (0)

No revisions yet.