I am looking to implement navigation buttons that will remain fixed vertically within a long table as the user scrolls through it. These buttons are intended to facilitate horizontal scrolling within the table, ensuring they stay contained within the table itself. When using 'fixed' positioning, the buttons break out of the table and become tied to the viewport. Adding translatez:(0) to the parent container causes the buttons to no longer move along with the center of the page.
document.addEventListener('DOMContentLoaded', function() {
const tableContainer = document.getElementById('table-container');
const scrollLeft = document.getElementById('scroll-left');
const scrollRight = document.getElementById('scroll-right');
let scrollInterval;
function updateArrows() {
scrollLeft.style.display = tableContainer.scrollLeft > 0 ? 'block' : 'none';
scrollRight.style.display = (tableContainer.scrollWidth > tableContainer.clientWidth) &&
(tableContainer.scrollLeft < tableContainer.scrollWidth - tableContainer.clientWidth) ? 'block' : 'none';
}
function startScrolling(direction) {
stopScrolling(); // Ensure no other scrolling is active
scrollInterval = setInterval(function() {
tableContainer.scrollBy({
left: direction === 'left' ? -10 : 10,
behavior: 'smooth'
});
}, 50); // Adjust scroll speed by changing the interval time or the scroll amount
}
function stopScrolling() {
clearInterval(scrollInterval);
}
scrollLeft.addEventListener('mousedown', function() {
startScrolling('left');
});
scrollRight.addEventListener('mousedown', function() {
startScrolling('right');
});
document.addEventListener('mouseup', stopScrolling);
document.addEventListener('mouseleave', stopScrolling);
tableContainer.addEventListener('scroll', updateArrows);
// Initial check
updateArrows();
});
.scroll-container {
position: relative;
display: flex;
align-items: center;
width: fit-content;
margin: 0 auto;
/* transform: translateZ(0);*/
}
.table-container {
overflow-x: auto;
white-space: nowrap;
width: 300px;
/* Adjust based on your design */
border: 1px solid #ddd;
position: relative;
/* Needed for absolute positioning of arrows */
}
.scroll-arrow {
position: fixed;
top: 50%;
transform: translateY(-50%);
background-color: #f1f1f1;
border: 1px solid #ddd;
padding: 5px;
cursor: pointer;
display: none;
z-index: 1;
}
#scroll-left {
left: 0;
}
#scroll-right {
right: 0;
}
/* Table styling */
table {
border-collapse: collapse;
}
th,
td {
border: 1px solid #ddd;
padding: 8px;
}
<p>Unique text goes here.</p>