javascripthtmlscrollhtml-tablescrollbars

Determine top row in html table


I have a html table with scrollbar (i.e. overflow is set). When I scroll the table, I would like to get the the current top-row in position (i.e. according to user-view of table).

How would I do this?

Can anyone of you help me with an example?


Solution

  • Here is something that might help get you started if you're going at it with vanilla JavaScript. It's definitely not perfect but might spark some ideas... JSFiddle Example

    [update] code from link above

    JavaScript

    document.getElementById('btn').onclick = function() {
        var tbl = document.getElementById('tbl');
        var scrollAmt = document.getElementById('asdf').scrollTop;
        var totalRowHeight = 0,
            viewTolerance = 1/3, //if only 1/3 of row is showing highlight next row
            rowHeight;
    
        for( var i = 0; i < tbl.rows.length; i++ ) {
            totalRowHeight += rowHeight = tbl.rows[i].offsetHeight;
            if( totalRowHeight > scrollAmt ) {
                //if row doesn't meet viewTolerance requirement highlight next row
                var rowIndex = (totalRowHeight - scrollAmt < rowHeight*viewTolerance) ? i + 1: i;
                tbl.rows[rowIndex].style.backgroundColor = '#ff00ff';
                break;
            }
        }
    }
    

    HTML

    <div id="asdf">
        <table id="tbl">
            <tbody>
                <tr><td>asdf</td><td>asdf1</td></tr>
                <tr><td>asdf</td><td>asdf2</td></tr>
                <tr><td>asdf</td><td>asdf3</td></tr>
                <tr><td>asdf</td><td>asdf4</td></tr>
                <tr><td>asdf</td><td>asdf5</td></tr>
                <tr><td>asdf</td><td>asdf6</td></tr>
                <tr><td>asdf</td><td>asdf7</td></tr>
                <tr><td>asdf</td><td>asdf8</td></tr>
            </tbody>
        </table>
    </div>
    <input type="button" value="getTop()" id="btn" />
    

    CSS

    #asdf{
        height:100px;
        overflow:scroll;
    }