Wednesday, November 26, 2014

JQuery : Scroll to nth row in a table.

<style type="text/css">

table{margin-top:20px;}

td{padding:3px;}

td:nth-child(1){color:red;}

tr.active{background-color:yellow;}

#control{
line-height:20px;
padding:3px;
position:fixed;
top:0;left:0;right:0;
background-color:#33b5e5;
}

</style>

<script type="text/javascript" src="jquery-1.11.1.min.js"></script> /* Link jQuery file here.. */


<div id="control">
    Line <input type="text" size="5" id="line" /> <button> go </button>
</div>
<table>
    <tr>
        <td></td>
        <td></td>
    </tr>
</table>


<script type="text/javascript">

// create and fill the table
var row = $('tr');
var table = $('table');

for (var i=1;i<100;i++){
   row.clone().appendTo( table );
}

table.find('tr').each(function(idx, elem){
   $(this).find('td:first').text(idx).end().find('td:last').text('This is the line '+(idx)+' of the table');
});

// code to scroll
$('#control button').click(function(){
   var w = $(window);
   var row = table.find('tr')
       .removeClass('active')
       .eq( +$('#line').val() )
       .addClass('active');
 
   if (row.length){
       w.scrollTop( row.offset().top - (w.height()/2) );
   }
});

</script>


Output :)

1)

2)

No comments:

Post a Comment