Javascript: Print content of particular div

 
Javascript: Print content of particular div

Hey, I faced some problems in one simple task. that is print with preview a particular selection of content(div content) or the content recived via ajax.

window.print();

The function print the whole page, which is not what we want.
Method 1:

$.ajax({
	type: "GET", url: the_url, data: {},
	success: function(data){
		var newWin = window.open();
		newWin.document.write(data);
		newWin.document.close();
		newWin.focus();
		newWin.print();
	}
	,error: function() {
	}
});

Its a common solution to solve this problems. its a good method but its had one drawback. pop-up blockers block any window that isn’t opened by a direct user action (such as clicking the mouse.) But since your ajax call is asynchronous, the browser doesn’t think it’s part of your button-click event. so we can off the asynchronous flag on call.

$.ajax({
	type: "GET", url: the_url, data: {},
	async: false,
	success:...

Now, it will works fine.
Method 2:

$.ajax({
	type: "GET", url: the_url, data: {},
	success: function(data){
		var iFrame = $('<iframe id="print_contentbox" style="min-width: 770px;height:100%;"></iframe>');
		$('body').append(iFrame);
		iFrame.dialog({
			modal: true,
			title: 'Preview',
			width: 800,
			height: 600,
			close: function(event, ui) {
				$(this).dialog('destroy').remove();
			}
		});
		var iFrameWin = iFrame[0].contentWindow;
		var iFrameDoc = iFrame[0].contentDocument || iFrameWin.document;
		iFrameDoc.write(response.content);
		iFrameDoc.close();
		iFrameWin.print();
	}
	,error: function() {
	}
});

Its a another one best method. here we create a blank iframe with jquery ui-dialog. and then can write our content. i think its ui styles are better then normal window preview.

“Can Anything 🙂 “