Posts Tagged ‘datatables’

Printing DataTables with scroller

Posted by

So you work with DataTables (datatables.net)? Nice to meet the few 100 of you.

Had to implement table virtualisation with the Scroller plug-in? Whoa! Down to 20.

Now hands up if you’ve had to deal with printing the table in Internet Explorer. 3. Wha?! Only 3!?

Well welcome to our collective world of pain. Alas there is a solution to the printing problem.

The problem

When you have a long table and you’ve scrolled half way down and found the data you want to print out and go to print, what do you expect? What you see on screen right? Nope, you get the top of the table.

This is the point some funky maths gets employed (whoever is telling you maths is a waste of time is lying to you kids!) to pull the table back up to where is was on screen. And of course, restoring the table to it’s original state once the printing has finished.

window.onbeforeprint = function() {
	'use strict';
	$('.dataTables_scrollBody').each(function(idx) {
		var table = $(this);
		var cache = {};

		table.dataTableSettings[idx].sDom = table.dataTableSettings[idx].sDom.replace(/S/, '');
		table.dataTableSettings[idx].oScroller.s.dt.bProcessing = false;
		table.dataTableSettings[idx].oScroller.s.skip = true;

		cache.oldTableTop = parseInt(table.find('table').css('top'), 10);
		cache.oldScrollTop = this.scrollTop;

		table.data('oldcss', cache);
		table.find('table').css({
			top: cache.oldTableTop - cache.oldScrollTop
		});
	});
};

window.onafterprint = function() {
	'use strict';
	$('.dataTables_scrollBody').each(function(idx) {
		var table = $(this);
		var cache = table.data('oldcss');

		table.dataTableSettings[idx].sDom = table.dataTableSettings[idx].sDom.replace(/S/, '') + 'S';
		table.dataTableSettings[idx].oScroller.s.dt.bProcessing = true;
		table.dataTableSettings[idx].oScroller.s.skip = false;

		table.scrollTop(cache.oldTableTop);
		table.find('table')
			.css({
				top: cache.oldTableTop + 'px'
			})
			.dataTable().api().draw(false);
	});
};

 

I couldn’t get this working with wide tables that force a horizontal scroll mind.