I’m trying to integrate a scroll bar to a dynamic table after the height is 275px. The scroll bar is functional after the table reaches 275px, however, when I use the table scroll bar, I do not see any change to the window.scrollY value. Instead, The scroll bar for the entire page is changing the value of window.scrollY, which is not what I need.
Here is a snippet of my table container:
// Define Table Container and add it to the parent container
var tableContainer = $('<div>').css({
'max-width': '55px',
'max-height': '275px',
'overflow-y': 'scroll',
'border': '1px solid black', // Add a border for visualization
});
let scrollPosition = 0;
function handleScroll() {
scrollPosition = window.scrollY;
console.log("PosY = ", scrollPosition);
}
let my_array = [
[1, 2, 3],
[4, 5, 6],
[1, 2, 3],
[4, 5, 6],
[1, 2, 3],
[4, 5, 6],
[1, 2, 3],
[4, 5, 6],
[1, 2, 3],
[4, 5, 6],
[1, 2, 3],
[4, 5, 6],
[1, 2, 3],
[4, 5, 6],
[1, 2, 3],
[4, 5, 6]
];
// Function to update and display the 'result'
function updateAndDisplayResult() {
// Loop through your data and populate the table
my_array.forEach(function(subArray) {
var row = $('<tr>'); // Create a row for each sub-array
subArray.forEach(function(item) {
var cell = $('<td>').text(item);
cell.css('border', '1px solid black'); // Add cell border
row.append(cell);
});
tableContainer.append(row); // Append the row to the table
});
// Finally, append the tableContainer to your document
$('#result').append(tableContainer);
};
window.addEventListener('scroll', handleScroll)
updateAndDisplayResult();
<div id="result"></div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
I’ve attached a few pictures to better clarify as well:
I’ve tried many things, but I’m stuck here. Any solutions to the following would be greatly appreciated:
- Link table scroll bar scrolly to window.scrollY value
- Hide scroll bar until the max-height defined.
Thanks in advance for any help!
2
Answers
So, i’ve removed the border on the table, since it keeps showing up even without the scrollbar, and the scrollbar is perfectly visible when it’s needed.
To display the table scrollbar just when it’s needed, instead of using
'overflow-y': 'scroll',
you can use'overflow-y': 'auto',
.The scrollPosition problem, is that you’ve attached it to the window, instead of the table in question.
I’ve changed the
scrollY
to thescrollTop()
function and youraddEventListener
to listen for the scroll action, for a.on('scroll')
.Now it’ll work as expected:
just add ‘tableContainer.scrollTop(scrollPosition)’ to the function named ‘handleScroll’ last line
or tableContainer.get(0).scrollTo({top: scrollPosition})
this is the sample code to sync scrolling is: