I have a horizontal list of links. When I click on the right button, I want to scroll the list to the right. When I click on the left button, I want to scroll the list to the left. I have the following code so far
How do I stop the scrolling to the right when I reach the end of the list? Also, how do I only scroll each time the width of the next element instead of the fixed amount 200?
document.addEventListener('DOMContentLoaded', function() {
const scrollAmount = 200; // Amount of pixels to scroll per click
const container = document.querySelector('.scrollable-list');
const btnRight = document.querySelector('.scroll-btn.right');
const btnLeft = document.querySelector('.scroll-btn.left');
btnRight.addEventListener('click', function() {
container.scrollBy({
left: scrollAmount,
behavior: 'smooth'
});
});
btnLeft.addEventListener('click', function() {
container.scrollBy({
left: -scrollAmount,
behavior: 'smooth'
});
});
});
.container {
display: flex;
align-items: center;
overflow: hidden;
}
.scrollable-list {
overflow-x: auto;
white-space: nowrap;
}
.scrollable-list ul {
list-style: none;
padding: 0;
margin: 0;
display: flex;
}
.scrollable-list li {
padding: 10px;
display: inline-block;
}
.scroll-btn {
cursor: pointer;
background: #ddd;
border: none;
padding: 10px 20px;
}
.scroll-btn:hover {
background: #ccc;
}
<div class="container">
<button class="scroll-btn left"><</button>
<div class="scrollable-list">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
<li>Item 7</li>
<li>Item 8</li>
<li>Item 9</li>
<!-- Add more list items as needed -->
</ul>
</div>
<button class="scroll-btn right">></button>
</div>
2
Answers
You have basically three options:
You build a list structure where every element has a fixed equal size, manage element content dinamically to increase or decrease font size depending on how much text you need to fit into the container, and scroll always a fixed amount of space equal to your elements size. You can simplify this approach showing always a fixed number of elements of screen, a number that you know you can dinamically adapt your content to any device screen or resolution without too much of a headache. So the idea is each click makes an element go away and another one coming into the screen from the outside.
You need to keep a track of which elements are on screen in every moment, which can be quite tricky as it implies reading screen resolution and make some calculations depending on it.
Ignore offsetting elements altoghether and just show or hide your elements keeping track of which of them should be on screen at every click. Use css animations to achieve your desired scrolling effect.
Personally I would go by this third approach, probably the most clean of them all