3 * @description Virtual rendering for DataTables
6 * @author Allan Jardine (www.sprymedia.co.uk)
7 * @license GPL v2 or BSD 3 point style
8 * @contact www.sprymedia.co.uk/contact
10 * @copyright Copyright 2011-2012 Allan Jardine, all rights reserved.
12 * This source file is free software, under either the GPL v2 license or a
13 * BSD style license, available at:
14 * http://datatables.net/license_gpl2
15 * http://datatables.net/license_bsd
18 (/** @lends <global> */function($, window, document) {
22 * Scroller is a virtual rendering plug-in for DataTables which allows large
23 * datasets to be drawn on screen every quickly. What the virtual rendering means
24 * is that only the visible portion of the table (and a bit to either side to make
25 * the scrolling smooth) is drawn, while the scrolling container gives the
26 * visual impression that the whole table is visible. This is done by making use
27 * of the pagination abilities of DataTables and moving the table around in the
28 * scrolling container DataTables adds to the page. The scrolling container is
29 * forced to the height it would be for the full table display using an extra
32 * Note that rows in the table MUST all be the same height. Information in a cell
33 * which expands on to multiple lines will cause some odd behaviour in the scrolling.
35 * Scroller is initialised by simply including the letter 'S' in the sDom for the
36 * table you want to have this feature enabled on. Note that the 'S' must come
37 * AFTER the 't' parameter in sDom.
39 * Key features include:
40 * <ul class="limit_length">
41 * <li>Speed! The aim of Scroller for DataTables is to make rendering large data sets fast</li>
42 * <li>Full compatibility with deferred rendering in DataTables 1.9 for maximum speed</li>
43 * <li>Correct visual scrolling implementation, similar to "infinite scrolling" in DataTable core</li>
44 * <li>Integration with state saving in DataTables (scrolling position is saved)</li>
45 * <li>Easy to use</li>
50 * @param {object} oDT DataTables settings object
51 * @param {object} [oOpts={}] Configuration object for FixedColumns. Options are defined by {@link Scroller.oDefaults}
53 * @requires jQuery 1.4+
54 * @requires DataTables 1.9.0+
57 * $(document).ready(function() {
58 * $('#example').dataTable( {
59 * "sScrollY": "200px",
60 * "sAjaxSource": "media/dataset/large.txt",
62 * "bDeferRender": true
66 var Scroller = function ( oDTSettings, oOpts ) {
67 /* Sanity check - you just know it will happen */
68 if ( ! this instanceof Scroller )
70 alert( "Scroller warning: Scroller must be initialised with the 'new' keyword." );
74 if ( typeof oOpts == 'undefined' )
80 * Settings object which contains customisable information for the Scroller instance
82 * @extends Scroller.DEFAULTS
86 * DataTables settings object
88 * @default Passed in as first parameter to constructor
93 * Pixel location of the top of the drawn table in the viewport
100 * Pixel location of the bottom of the drawn table in the viewport
107 * Pixel location of the boundary for when the next data set should be loaded and drawn
108 * when scrolling up the way.
116 * Pixel location of the boundary for when the next data set should be loaded and drawn
117 * when scrolling down the way. Note that this is actually caluated as the offset from
126 * Height of rows in the table
133 * Auto row height or not indicator
140 * Pixel height of the viewport
147 * Number of rows calculated as visible in the visible viewport
154 * setTimeout reference for state saving, used when state saving is enabled in the DataTable
155 * and when the user scrolls the viewport in order to stop the cookie set taking too much
163 * setTimeout reference for the redraw, used when server-side processing is enabled in the
164 * DataTables in order to prevent DoSing the server
170 this.s = $.extend( this.s, Scroller.oDefaults, oOpts );
173 * DOM elements used by the class instance
178 "force": document.createElement('div'),
183 /* Attach the instance to the DataTables instance so it can be accessed */
184 this.s.dt.oScroller = this;
192 Scroller.prototype = {
193 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
195 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
198 * Calculate the pixel position from the top of the scrolling container for a given row
199 * @param {int} iRow Row number to calculate the position of
200 * @returns {int} Pixels
202 * $(document).ready(function() {
203 * $('#example').dataTable( {
204 * "sScrollY": "200px",
205 * "sAjaxSource": "media/dataset/large.txt",
207 * "bDeferRender": true,
208 * "fnInitComplete": function (o) {
209 * // Find where row 25 is
210 * alert( o.oScroller.fnRowToPixels( 25 ) );
215 "fnRowToPixels": function ( iRow )
217 return iRow * this.s.rowHeight;
222 * Calculate the row number that will be found at the given pixel position (y-scroll)
223 * @param {int} iPixels Offset from top to caluclate the row number of
224 * @returns {int} Row index
226 * $(document).ready(function() {
227 * $('#example').dataTable( {
228 * "sScrollY": "200px",
229 * "sAjaxSource": "media/dataset/large.txt",
231 * "bDeferRender": true,
232 * "fnInitComplete": function (o) {
233 * // Find what row number is at 500px
234 * alert( o.oScroller.fnPixelsToRow( 500 ) );
239 "fnPixelsToRow": function ( iPixels )
241 return parseInt( iPixels / this.s.rowHeight, 10 );
246 * Calculate the row number that will be found at the given pixel position (y-scroll)
247 * @param {int} iRow Row index to scroll to
248 * @param {bool} [bAnimate=true] Animate the transision or not
251 * $(document).ready(function() {
252 * $('#example').dataTable( {
253 * "sScrollY": "200px",
254 * "sAjaxSource": "media/dataset/large.txt",
256 * "bDeferRender": true,
257 * "fnInitComplete": function (o) {
258 * // Immediately scroll to row 1000
259 * o.oScroller.fnScrollToRow( 1000 );
263 * // Sometime later on use the following to scroll to row 500...
264 * var oSettings = $('#example').dataTable().fnSettings();
265 * oSettings.oScroller.fnScrollToRow( 500 );
268 "fnScrollToRow": function ( iRow, bAnimate )
270 var px = this.fnRowToPixels( iRow );
271 if ( typeof bAnimate == 'undefined' || bAnimate )
273 $(this.dom.scroller).animate( {
279 $(this.dom.scroller).scrollTop( px );
285 * Calculate and store information about how many rows are to be displayed in the scrolling
286 * viewport, based on current dimensions in the browser's rendering. This can be particularly
287 * useful if the table is initially drawn in a hidden element - for example in a tab.
288 * @param {bool} [bRedraw=true] Redraw the table automatically after the recalculation, with
289 * the new dimentions forming the basis for the draw.
292 * $(document).ready(function() {
293 * // Make the example container hidden to throw off the browser's sizing
294 * document.getElementById('container').style.display = "none";
295 * var oTable = $('#example').dataTable( {
296 * "sScrollY": "200px",
297 * "sAjaxSource": "media/dataset/large.txt",
299 * "bDeferRender": true,
300 * "fnInitComplete": function (o) {
301 * // Immediately scroll to row 1000
302 * o.oScroller.fnScrollToRow( 1000 );
306 * setTimeout( function () {
307 * // Make the example container visible and recalculate the scroller sizes
308 * document.getElementById('container').style.display = "block";
309 * oTable.fnSettings().oScroller.fnMeasure();
312 "fnMeasure": function ( bRedraw )
314 if ( this.s.autoHeight )
316 this._fnCalcRowHeight();
319 this.s.viewportHeight = $(this.dom.scroller).height();
320 this.s.viewportRows = parseInt( this.s.viewportHeight/this.s.rowHeight, 10 )+1;
321 this.s.dt._iDisplayLength = this.s.viewportRows * this.s.displayBuffer;
326 'Row height: '+this.s.rowHeight +' '+
327 'Viewport height: '+this.s.viewportHeight +' '+
328 'Viewport rows: '+ this.s.viewportRows +' '+
329 'Display rows: '+ this.s.dt._iDisplayLength
333 if ( typeof bRedraw == 'undefined' || bRedraw )
335 this.s.dt.oInstance.fnDraw();
341 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
342 * Private methods (they are of course public in JS, but recommended as private)
343 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
346 * Initialisation for Scroller
350 "_fnConstruct": function ()
354 /* Insert a div element that we can use to force the DT scrolling container to
355 * the height that would be required if the whole table was being displayed
357 this.dom.force.style.position = "absolute";
358 this.dom.force.style.top = "0px";
359 this.dom.force.style.left = "0px";
360 this.dom.force.style.width = "1px";
362 this.dom.scroller = $('div.'+this.s.dt.oClasses.sScrollBody, this.s.dt.nTableWrapper)[0];
363 this.dom.scroller.appendChild( this.dom.force );
364 this.dom.scroller.style.position = "relative";
366 this.dom.table = $('>table', this.dom.scroller)[0];
367 this.dom.table.style.position = "absolute";
368 this.dom.table.style.top = "0px";
369 this.dom.table.style.left = "0px";
371 // Add class to 'announce' that we are a Scroller table
372 $(this.s.dt.nTableWrapper).addClass('DTS');
374 // Add a 'loading' indicator
375 if ( this.s.loadingIndicator )
377 $(this.dom.scroller.parentNode)
378 .css('position', 'relative')
379 .append('<div class="DTS_Loading">'+this.s.dt.oLanguage.sLoadingRecords+'</div>');
382 /* Initial size calculations */
383 if ( this.s.rowHeight && this.s.rowHeight != 'auto' )
385 this.s.autoHeight = false;
387 this.fnMeasure( false );
389 /* Scrolling callback to see if a page change is needed */
390 $(this.dom.scroller).scroll( function () {
391 that._fnScroll.call( that );
394 /* In iOS we catch the touchstart event incase the user tries to scroll
395 * while the display is already scrolling
397 $(this.dom.scroller).bind('touchstart', function () {
398 that._fnScroll.call( that );
401 /* Update the scroller when the DataTable is redrawn */
402 this.s.dt.aoDrawCallback.push( {
404 if ( that.s.dt.bInitialised ) {
405 that._fnDrawCallback.call( that );
411 /* Add a state saving parameter to the DT state saving so we can restore the exact
412 * position of the scrolling
414 this.s.dt.oApi._fnCallbackReg( this.s.dt, 'aoStateSaveParams', function (oS, oData) {
415 oData.iScroller = that.dom.scroller.scrollTop;
416 }, "Scroller_State" );
421 * Scrolling function - fired whenever the scrolling position is changed. This method needs
422 * to use the stored values to see if the table should be redrawn as we are moving towards
423 * the end of the information that is currently drawn or not. If needed, then it will redraw
424 * the table based on the new position.
428 "_fnScroll": function ()
432 iScrollTop = this.dom.scroller.scrollTop,
435 /* If the table has been sorted or filtered, then we use the redraw that
436 * DataTables as done, rather than performing our own
438 if ( this.s.dt.bFiltered || this.s.dt.bSorted )
446 'Scroll: '+iScrollTop+'px - boundaries: '+this.s.redrawTop+' / '+this.s.redrawBottom+'. '+
447 ' Showing rows '+this.fnPixelsToRow(iScrollTop)+
448 ' to '+this.fnPixelsToRow(iScrollTop+$(this.dom.scroller).height())+
449 ' in the viewport, with rows '+this.s.dt._iDisplayStart+
450 ' to '+(this.s.dt._iDisplayEnd)+' rendered by the DataTable'
454 /* Update the table's information display for what is now in the viewport */
457 /* We dont' want to state save on every scroll event - that's heavy handed, so
458 * use a timeout to update the state saving only when the scrolling has finished
460 clearTimeout( this.s.stateTO );
461 this.s.stateTO = setTimeout( function () {
462 that.s.dt.oApi._fnSaveState( that.s.dt );
465 /* Check if the scroll point is outside the trigger boundary which would required
466 * a DataTables redraw
468 if ( iScrollTop < this.s.redrawTop || iScrollTop > this.s.redrawBottom )
470 var preRows = ((this.s.displayBuffer-1)/2) * this.s.viewportRows;
471 iTopRow = parseInt( iScrollTop / this.s.rowHeight, 10 ) - preRows;
474 /* At the start of the table */
477 else if ( iTopRow + this.s.dt._iDisplayLength > this.s.dt.fnRecordsDisplay() )
479 /* At the end of the table */
480 iTopRow = this.s.dt.fnRecordsDisplay() - this.s.dt._iDisplayLength;
486 else if ( iTopRow % 2 !== 0 )
488 /* For the row-striping classes (odd/even) we want only to start on evens
489 * otherwise the stripes will change between draws and look rubbish
494 if ( iTopRow != this.s.dt._iDisplayStart )
496 /* Cache the new table position for quick lookups */
497 this.s.tableTop = $(this.s.dt.nTable).offset().top;
498 this.s.tableBottom = $(this.s.dt.nTable).height() + this.s.tableTop;
500 /* Do the DataTables redraw based on the calculated start point - note that when
501 * using server-side processing we introduce a small delay to not DoS the server...
503 if ( this.s.dt.oFeatures.bServerSide ) {
504 clearTimeout( this.s.drawTO );
505 this.s.drawTO = setTimeout( function () {
506 that.s.dt._iDisplayStart = iTopRow;
507 that.s.dt.oApi._fnCalculateEnd( that.s.dt );
508 that.s.dt.oApi._fnDraw( that.s.dt );
509 }, this.s.serverWait );
513 this.s.dt._iDisplayStart = iTopRow;
514 this.s.dt.oApi._fnCalculateEnd( this.s.dt );
515 this.s.dt.oApi._fnDraw( this.s.dt );
520 console.log( 'Scroll forcing redraw - top DT render row: '+ iTopRow );
528 * Draw callback function which is fired when the DataTable is redrawn. The main function of
529 * this method is to position the drawn table correctly the scrolling container for the rows
530 * that is displays as a result of the scrolling position.
534 "_fnDrawCallback": function ()
538 iScrollTop = this.dom.scroller.scrollTop,
539 iScrollBottom = iScrollTop + this.s.viewportHeight;
541 /* Set the height of the scrolling forcer to be suitable for the number of rows
544 this.dom.force.style.height = (this.s.rowHeight * this.s.dt.fnRecordsDisplay())+"px";
546 /* Calculate the position that the top of the table should be at */
547 var iTableTop = (this.s.rowHeight*this.s.dt._iDisplayStart);
548 if ( this.s.dt._iDisplayStart === 0 )
552 else if ( this.s.dt._iDisplayStart === this.s.dt.fnRecordsDisplay() - this.s.dt._iDisplayLength )
554 iTableTop = this.s.rowHeight * this.s.dt._iDisplayStart;
557 this.dom.table.style.top = iTableTop+"px";
559 /* Cache some information for the scroller */
560 this.s.tableTop = iTableTop;
561 this.s.tableBottom = $(this.s.dt.nTable).height() + this.s.tableTop;
563 this.s.redrawTop = iScrollTop - ( (iScrollTop - this.s.tableTop) * this.s.boundaryScale );
564 this.s.redrawBottom = iScrollTop + ( (this.s.tableBottom - iScrollBottom) * this.s.boundaryScale );
569 "Table redraw. Table top: "+iTableTop+"px "+
570 "Table bottom: "+this.s.tableBottom+" "+
571 "Scroll boundary top: "+this.s.redrawTop+" "+
572 "Scroll boundary bottom: "+this.s.redrawBottom+" "+
573 "Rows drawn: "+this.s.dt._iDisplayLength);
576 /* Because of the order of the DT callbacks, the info update will
577 * take precidence over the one we want here. So a 'thread' break is
580 setTimeout( function () {
581 that._fnInfo.call( that );
584 /* Restore the scrolling position that was saved by DataTable's state saving
585 * Note that this is done on the second draw when data is Ajax sourced, and the
586 * first draw when DOM soured
588 if ( this.s.dt.oFeatures.bStateSave && this.s.dt.oLoadedState !== null &&
589 typeof this.s.dt.oLoadedState.iScroller != 'undefined' )
591 if ( (this.s.dt.sAjaxSource !== null && this.s.dt.iDraw == 2) ||
592 (this.s.dt.sAjaxSource === null && this.s.dt.iDraw == 1) )
594 setTimeout( function () {
595 $(that.dom.scroller).scrollTop( that.s.dt.oLoadedState.iScroller );
596 that.s.redrawTop = that.s.dt.oLoadedState.iScroller - (that.s.viewportHeight/2);
604 * Automatic calculation of table row height. This is just a little tricky here as using
605 * initialisation DataTables has tale the table out of the document, so we need to create
606 * a new table and insert it into the document, calculate the row height and then whip the
611 "_fnCalcRowHeight": function ()
613 var nTable = this.s.dt.nTable.cloneNode( false );
615 '<div class="'+this.s.dt.oClasses.sWrapper+' DTS">'+
616 '<div class="'+this.s.dt.oClasses.sScrollWrapper+'">'+
617 '<div class="'+this.s.dt.oClasses.sScrollBody+'"></div>'+
630 $('div.'+this.s.dt.oClasses.sScrollBody, nContainer).append( nTable );
632 document.body.appendChild( nContainer );
633 this.s.rowHeight = $('tbody tr', nTable).outerHeight();
634 document.body.removeChild( nContainer );
639 * Update any information elements that are controlled by the DataTable based on the scrolling
640 * viewport and what rows are visible in it. This function basically acts in the same way as
641 * _fnUpdateInfo in DataTables, and effectively replaces that function.
645 "_fnInfo": function ()
647 if ( !this.s.dt.oFeatures.bInfo )
654 iScrollTop = this.dom.scroller.scrollTop,
655 iStart = this.fnPixelsToRow(iScrollTop)+1,
656 iMax = dt.fnRecordsTotal(),
657 iTotal = dt.fnRecordsDisplay(),
658 iPossibleEnd = this.fnPixelsToRow(iScrollTop+$(this.dom.scroller).height()),
659 iEnd = iTotal < iPossibleEnd ? iTotal : iPossibleEnd,
660 sStart = dt.fnFormatNumber( iStart ),
661 sEnd = dt.fnFormatNumber( iEnd ),
662 sMax = dt.fnFormatNumber( iMax ),
663 sTotal = dt.fnFormatNumber( iTotal ),
666 if ( dt.fnRecordsDisplay() === 0 &&
667 dt.fnRecordsDisplay() == dt.fnRecordsTotal() )
669 /* Empty record set */
670 sOut = dt.oLanguage.sInfoEmpty+ dt.oLanguage.sInfoPostFix;
672 else if ( dt.fnRecordsDisplay() === 0 )
674 /* Rmpty record set after filtering */
675 sOut = dt.oLanguage.sInfoEmpty +' '+
676 dt.oLanguage.sInfoFiltered.replace('_MAX_', sMax)+
677 dt.oLanguage.sInfoPostFix;
679 else if ( dt.fnRecordsDisplay() == dt.fnRecordsTotal() )
681 /* Normal record set */
682 sOut = dt.oLanguage.sInfo.
683 replace('_START_', sStart).
684 replace('_END_', sEnd).
685 replace('_TOTAL_', sTotal)+
686 dt.oLanguage.sInfoPostFix;
690 /* Record set after filtering */
691 sOut = dt.oLanguage.sInfo.
692 replace('_START_', sStart).
693 replace('_END_', sEnd).
694 replace('_TOTAL_', sTotal) +' '+
695 dt.oLanguage.sInfoFiltered.replace('_MAX_',
696 dt.fnFormatNumber(dt.fnRecordsTotal()))+
697 dt.oLanguage.sInfoPostFix;
700 var n = dt.aanFeatures.i;
701 if ( typeof n != 'undefined' )
703 for ( var i=0, iLen=n.length ; i<iLen ; i++ )
705 $(n[i]).html( sOut );
713 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
715 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
719 * Scroller default settings for initialisation
723 Scroller.oDefaults = {
725 * Indicate if Scroller show show trace information on the console or not. This can be
726 * useful when debugging Scroller or if just curious as to what it is doing, but should
727 * be turned off for production.
732 * var oTable = $('#example').dataTable( {
733 * "sScrollY": "200px",
735 * "bDeferRender": true,
744 * Scroller will attempt to automatically calculate the height of rows for it's internal
745 * calculations. However the height that is used can be overridden using this parameter.
750 * var oTable = $('#example').dataTable( {
751 * "sScrollY": "200px",
753 * "bDeferRender": true,
762 * When using server-side processing, Scroller will wait a small amount of time to allow
763 * the scrolling to finish before requesting more data from the server. This prevents
764 * you from DoSing your own server! The wait time can be configured by this parameter.
769 * var oTable = $('#example').dataTable( {
770 * "sScrollY": "200px",
772 * "bDeferRender": true,
781 * The display buffer is what Scroller uses to calculate how many rows it should pre-fetch
782 * for scrolling. Scroller automatically adjusts DataTables' display length to pre-fetch
783 * rows that will be shown in "near scrolling" (i.e. just beyond the current display area).
784 * The value is based upon the number of rows that can be displayed in the viewport (i.e.
785 * a value of 1), and will apply the display range to records before before and after the
786 * current viewport - i.e. a factor of 3 will allow Scroller to pre-fetch 1 viewport's worth
787 * of rows before the current viewport, the current viewport's rows and 1 viewport's worth
788 * of rows after the current viewport. Adjusting this value can be useful for ensuring
789 * smooth scrolling based on your data set.
794 * var oTable = $('#example').dataTable( {
795 * "sScrollY": "200px",
797 * "bDeferRender": true,
799 * "displayBuffer": 10
806 * Scroller uses the boundary scaling factor to decide when to redraw the table - which it
807 * typically does before you reach the end of the currently loaded data set (in order to
808 * allow the data to look continuous to a user scrolling through the data). If given as 0
809 * then the table will be redrawn whenever the viewport is scrolled, while 1 would not
810 * redraw the table until the currently loaded data has all been shown. You will want
811 * something in the middle - the default factor of 0.5 is usually suitable.
816 * var oTable = $('#example').dataTable( {
817 * "sScrollY": "200px",
819 * "bDeferRender": true,
821 * "boundaryScale": 0.75
825 "boundaryScale": 0.5,
828 * Show (or not) the loading element in the background of the table. Note that you should
829 * include the dataTables.scroller.css file for this to be displayed correctly.
834 * var oTable = $('#example').dataTable( {
835 * "sScrollY": "200px",
837 * "bDeferRender": true,
839 * "loadingIndicator": true
843 "loadingIndicator": false
848 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
850 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
859 Scroller.prototype.CLASS = "Scroller";
868 Scroller.VERSION = "1.1.0";
869 Scroller.prototype.VERSION = Scroller.VERSION;
873 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
875 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
878 * Register a new feature with DataTables
880 if ( typeof $.fn.dataTable == "function" &&
881 typeof $.fn.dataTableExt.fnVersionCheck == "function" &&
882 $.fn.dataTableExt.fnVersionCheck('1.9.0') )
884 $.fn.dataTableExt.aoFeatures.push( {
885 "fnInit": function( oDTSettings ) {
886 var init = (typeof oDTSettings.oInit.oScroller == 'undefined') ?
887 {} : oDTSettings.oInit.oScroller;
888 var oScroller = new Scroller( oDTSettings, init );
889 return oScroller.dom.wrapper;
892 "sFeature": "Scroller"
897 alert( "Warning: Scroller requires DataTables 1.9.0 or greater - www.datatables.net/download");
901 // Attach Scroller to DataTables so it can be accessed as an 'extra'
902 $.fn.dataTable.Scroller = Scroller;
904 })(jQuery, window, document);