I have written the following code to scroll an element 20 more pixels to the right.
const button = document.getElementById('slide');
button.onclick = function () {
document.getElementById('container').scrollLeft += 20;
};
How can I make the scrolling smooth? I have tried using Element#scroll like so:
const button = document.getElementById('slide');
button.onclick = function () {
document.getElementById('container').scroll({
left: += 20,
behavior: smooth
});
};
Am I able to do this?
You can use Element#scrollBy to scroll a certain amount from the current position.
button.onclick = function () {
document.getElementById('container').scrollBy({
left: 20,
behavior: 'smooth'
});
};
Is this what you are looking for?
From MDN:
scrollBy()scrolls by a particular amount, whereasscroll()scrolls to an absolute position in the document.
https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollBy
const container = document.querySelector("#container");
const button = document.querySelector("#btnScroll");
button.addEventListener('click', e => {
container.scrollBy({
left: 200,
behavior: 'smooth'
});
});
#container {
position: relative;
max-width: 200px;
overflow-x: scroll;
display: flex;
margin: 20px;
}
img {
display: inline-block
}
<div id="container">
<img src="https://dummyimage.com/200x100/000/fff">
<img src="https://dummyimage.com/200x100/0f0/000">
<img src="https://dummyimage.com/200x100/00f/fff">
<img src="https://dummyimage.com/200x100/f00/fff">
</div>
<button id="btnScroll">Scroll 200px</button>