neo
neo

Reputation: 2471

JQuery: How to calculate the number of rows to show within a container

kinda hard to explain, but let me try:
I'd like to put a table inside a container . this container has a fixed height, say 500px, and the table is rather long, say 2100 and each row's height can be different.

When the table is created, all the rows are invisible, now I want to do a calculation based on container's height to find out how many rows should appear inside the container. it could be first 15 rows, or first 17 rows (because some row's height is bigger).

After I do that, I let those rows stay there for some time, and hide them again, and do another calculation to fetch next page, and so on... Now the hard part it how do I do the calculation using jquery?

Upvotes: 0

Views: 266

Answers (4)

DACrosby
DACrosby

Reputation: 11460

This doesn't tackle the "stay for a while and fetch next set of rows after a while" part, but here's a simple calculation for heights that shows the appropriate rows.

http://jsfiddle.net/yvAtW/

JS

allowedHeight = $("div").height();
actualHeight = 0;

$("tr").each(function(){
    actualHeight += $(this).height();
    if(actualHeight < allowedHeight) {
        $(this).show();
    }
});
​

HTML

<div>
<table>
    <tr class="height0">
        <td>Row</td>
    </tr>
    <tr class="height1">
        <td>Row</td>
    </tr>
    <tr class="height2">
        <td>Row</td>
    </tr>
    <tr class="height1">
        <td>Row</td>
    </tr>
    <tr class="height0">
        <td>Row</td>
    </tr>
</table>
</div>​

CSS

div{
    height:100px; /* fixed height container */
    overflow:hidden; /* Ensures no overflowing content if JS doesn't work */
    padding:10px 15px;
    background:#777;
}
table{
    width:100%;
}
tr{
    display:none; /* all hidden by default */
}
/* different height trs */
.height0{
    height:20px;
    background:#900;
}
.height1{
    height:30px;
    background:#090;
}
.height2{
    height:40px;
    background:#009;
}​

Upvotes: 1

Isaac Gonzalez
Isaac Gonzalez

Reputation: 1734

perhaps you can do something like this:

fits = true;
while(fits){
    $(table).append('<tr>...</tr>');

    if($(table).css('height') >= $('#container').css('height'))
        fits = false;
}

Upvotes: -1

Travis J
Travis J

Reputation: 82297

Iterate through the rows summing their height. Once you get over 500, take the set of rows except for the last row. Display those. Keep track of where you are at with some sort of marker, maybe a variable or a data- annotation.

Upvotes: 0

Snow Blind
Snow Blind

Reputation: 1164

You can get the heights computed by the browser by using jQuery.innerHeight and jQuery.outerHeight functions. So you can first get the computed height of the container. Then you can iterate through rows and add their computed height until the sum is bigger than the container's computed height and so on..

Hope this helps.

Upvotes: 1

Related Questions