PDA

View Full Version : Moving the div scroll position to the nth (index) row in an HTML table row



jason_kelly
05-26-2014, 03:38 AM
Hello Guru's and Experts!

I really need your help with this one.

How can I add functionality to my existing jQuery javascript code using the function highlight() to not only highlight the specified target row, but to also move the div container scroll position to the nth (index) row in an HTML table?

I am jQuery friendly.

Here is my current HTML markup:



<!DOCTYPE html>

<html>

<head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<style type="text/css">
#data_container {
height: 100px;
border: 1px solid red;
width: auto;
overflow: scroll;
}
.highlight {

background-color: rgb(255,0,0);

}

</style>

<script type="text/javascript">

window.onload = function() {

var rowCount = $('#data tbody tr').length

$("#maxrows").val(rowCount)

function highlight(tableIndex) {

// Just a simple check. If .highlight has reached the last, start again
if( (tableIndex+1) > rowCount) {

tableIndex = 0;
}
// Element exists?
if($('#data tbody tr:eq('+tableIndex+')').length > 0) {
// Remove other highlights
$('#data tbody tr').removeClass('highlight');

// Highlight your target
$('#data tbody tr:eq('+tableIndex+')').addClass('highlight');

$("#rownum").val(tableIndex+1)
}
else {
$("#rownum").val(0)
}
}



$( "#data tbody tr" ).click(function() {
highlight($(this).index());
});


}


</script>

</head>

<body>


<div id="data_container">
<table id="data" border="1" cellspacing="1" cellpadding="1">

<thead>
<tr>
<th>#</th>
<th>Color</th>
<th>Fruit</th>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>red</td>
<td>kiwi</td>
<td>Lindsay</td>
<td>closed</td>
</tr>
<tr>
<td>2</td>
<td>blue</td>
<td>mangos</td>
<td>Sarah</td>
<td>open</td>
</tr>
<tr>
<td>3</td>
<td>green</td>
<td>oranges</td>
<td>Joseph</td>
<td>hold</td>
</tr>
<tr>
<td>4</td>
<td>yellow</td>
<td>pears</td>
<td>Jenny</td>
<td>open</td>
</tr>
<tr>
<td>5</td>
<td>orange</td>
<td>bananas</td>
<td>Mike</td>
<td>closed</td>
</tr>
<tr>
<td>6</td>
<td>purple</td>
<td>lemon</td>
<td>Jerry</td>
<td>open</td>
</tr>
<tr>
<td>7</td>
<td>teal</td>
<td>apples</td>
<td>Larry</td>
<td>hold</td>
</tr>
</tbody>
</table>
</div>
Row Number:
<br>
<input type="text" id="rownum"><br>
of
<br>
<input type="text" id="maxrows" readonly>
<br>
<input type="button" id="goto_first" value="first">
<input type="button" id="goto_prev" value="prev">
<input type="button" id="goto_next" value="next">
<input type="button" id="goto_last" value="last">
<input type="button" id="goto_row" value="goto row">
<input type="button" id="remove_row" value="remove row">
<br>
Color<input type="text" id="colors">
Fruit<input type="text" id="fruits">
Name<input type="text" id="names">
Status<input type="text" id="status">

</body>
</html>