Francis Francis - 1 month ago 10
CSS Question

Trying to print a div retaining original css content of the div but button is not clicking

I am trying to print a div retaining original css content of the div and here is my attempt

JS :

function printDiv(id) {

var html = "";

$('link').each(function() { // find all <link tags that have
if ($(this).attr('rel').indexOf('stylesheet') !=-1) { // rel="stylesheet"
html += '<link rel="stylesheet" href="'+$(this).attr("href")+'" />';
}
});
html += '<body onload="window.focus(); window.print()">+$("#"+id).html()+'</body>';
var w = window.open("","print");
if (w) { w.document.write(html); w.document.close() }

}

$('#PrintinPopup').click(function(){ printDiv("#print"); });


Assuming that this is the div content.

HTML :

<div id="print">
<!--div content here-->
</div>
<input type="button" id="PrintinPopup" value="Print" />


On clicking the button, nothing happens as no pop up is shown on the window. Please what could be wrong?

Answer

You've a missing quote in :

html += '<body onload="window.focus(); window.print()">+$("#"+id).html()+'</body>';
______________________________________________________^^

It should be :

html += '<body onload="window.focus(); window.print()">'+$("#"+id).html()+'</body>';
_______________________________________________________^

Also remove the '#' since you already send it in the call printDiv("#print") :

html += '<body onload="window.focus(); window.print()">'+$("#"+id).html()+'</body>';
___________________________________________________________^^^^

Should be :

html += '<body onload="window.focus(); window.print()">'+$(id).html()+'</body>';

Hope this helps.

Comments