Roland Seuhs
Roland Seuhs

Reputation: 1995

Javascript: Make table fit on screen vertically by hiding rows

I have an (almost) "endless" table (those kind of things which are typically shown only a certain amount of rows and a navigation bar below to show the next page, for example "show next 30 results" or "show next page").

The rows have also variable heights.

Is there a way to hide all rows that don't fit on the screen so that the whole table reliably fits on the page and the navigation row at the end is always visible without scrolling?

The idea is basically to send to the browser a simple HTML-table, like this:

<table>
<tr><th>Data1</th><td>More data</td></tr>
<tr><th>Data2</th><td>More<br>data<br>in<br>larger<br>row</td></tr>
<tr><th>Data3</th><td>More data that may be wrapped around because the user may not have a wide enough window for it</td></tr>
<tr><th>Data4</th><td>More data</td></tr>
<tr><th>Data5</th><td>More data</td></tr>
<tr><th>Data6</th><td>More data</td></tr>
<tr><th>Data7</th><td>More data</td></tr>
<tr><th>Data8</th><td>More data</td></tr>
<tr><th>Data9</th><td>More data</td></tr>
<tr><th colspan=2>NAVIGATION ROW</th></tr>
</table>

If for example only rows 1-4 (plus navigation row) fit on the screen, rows 5 to 9 should be hidden/collapsed and <input type=hidden name=lastrow value=4> set (or some equivalent to know where to continue on the next page).

That way the content should always fit the screen and the user would never need to scroll.

The table is the only visible thing on the page.

PS: The solution from this question works only with equal-height rows and is not applicable for variable height rows.

Is it possible?

Upvotes: 0

Views: 323

Answers (1)

roryok
roryok

Reputation: 9645

Should be easy enough. OnLoad the browser needs to look at

  1. The height of the window
  2. The height of the Table
  3. The vertical offset value of the table

if the Table + offset is taller than the window, then remove a row from the bottom until this is not true

lets give your table an ID of "myTable"

$(function(){
    // on load, run shrinkTable
    shrinkTable();
});

function shrinkTable(){
    if($("#myTable tr").length > 0){
        if(($("#myTable").height() + $("#myTable").offset().top) >  $(window).height()){
            $('#myTable tr:not(.navrow):last').remove();
            // run itself again!
            // this will run in a loop until the top condition is no longer met. 
            shrinkTable();
        }
    }
}

Fiddle: http://jsfiddle.net/sqay450r/

The only issue you'll face is that you'll then have to inform "page 2" about how many rows you deleted or else you'll be skipping data

UPDATE:

Changed the script to not remove the Navigation Row. I added a "navrow" class for that. I also added a second condition to check if the table has no rows, in case we remove them all and enter an infinite loop

Upvotes: 1

Related Questions