GEspinha GEspinha - 5 months ago 9
HTML Question

Scroll an object to the right

I have a

div
with an
overflow: scroll
. How can I make it scroll 20px to the right in javascript?

I tried the following but it doesn't seem work:

document.querySelector('div').scrollTo(20, 0);


It returns that
scrollTo
isn't a function.

Answer

scrollTo is not a function. What you want to use is scrollLeft. This will scroll your div to the right.

document.querySelector('div').scrollLeft = 20;

If you want to scroll 20 pixels to the right every time, use +=

document.querySelector('div').scrollLeft += 20;

If you want to scroll vertically, use the scrollTop property.

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft