I am trying to scroll into a particular row of a table; the div along with the table inside it, both have overflow:auto. This is my code for scrolling to a particular index of the table:
var table1 = document.getElementById("old_table");
table1.rows[3].scrollIntoView({
behavior: 'smooth',
block: 'center'
});
This is my html:
<div id="old_slab"><table id="old_table" border="2"></table></div>
And my css:
#old_slab{
position: absolute;
top:34em;
left:30em;
width:40em;
height: 15em;
overflow: auto;
}
#old_table{
height: 15em;
overflow: auto;
width: 40em;
}
The rows in my table are dynamically created, hence they are not hardcoded in my html code. Nevertheless, the table isn't empty. For some reason, the scrollIntoView() isn't working and I don't know why. Please help.
EDIT: Strangely, when I remove the behaviour and block arguments, then it works:
table1.rows[3].scrollIntoView(true);
It appears that .scrollIntoView() works on a properly referenced element whether dynamic added or not. The example below has 2 buttons proving it.
const scrollToRow = (selector, index) => {
const table = document.querySelector(selector);
const row = table.rows;
row[index].scrollIntoView({
behavior: 'smooth',
block: 'center'
});
};
document.querySelector('.scroll').onclick = function(e) {
scrollToRow('table', 3);
}
/* The following code is to simulate
dynamically added rows */
const addRow = selector => {
const table = document.querySelector('table');
const row = table.insertRow(0);
const cell = row.insertCell(0);
cell.colSpan = 2;
};
document.querySelector('.add').onclick = function() {
addRow('table');
};
section {
width: 40em;
height: 15em;
padding: 10%
}
table {
height: 15em;
width: 40em;
border: 2px solid black
}
td {
border: 2px solid black;
}
td::before {
content: '\a0';
}
button {
display: inline-block;
margin-bottom: 30%;
}
<button class='add'>Add Row</button>
<button class='scroll'>Scroll to Row 4</button>
<section>
<table>
<tr><td> </td><td> </td></tr>
<tr><td> </td><td> </td></tr>
<tr><td> </td><td> </td></tr>
<tr><td> </td><td> </td></tr>
<tr><td> </td><td> </td></tr>
<tr><td> </td><td> </td></tr>
<tr><td> </td><td> </td></tr>
<tr><td> </td><td> </td></tr>
<tr><td> </td><td> </td></tr>
<tr><td> </td><td> </td></tr>
<tr><td> </td><td> </td></tr>
<tr><td> </td><td> </td></tr>
<tr><td> </td><td> </td></tr>
<tr><td> </td><td> </td></tr>
<tr><td> </td><td> </td></tr>
<tr><td> </td><td> </td></tr>
</table>
<section>