I have a div with overflow: scroll;
And I would like to put a button. When you press it, the content of the div
scrolls.
Something like:
function scrollDiv() {
document.getElementById("d").scrollBy(100, 100);
}
<div id="d">
<p>Click the button to scroll by 100px.</p>
<button onclick="scrollDiv()">Click me to scroll!</button>
</div>
This works in FF, but not in Chrome. In Chrome I get
Uncaught TypeError: undefined is not a function
The scrollBy
function seems to be defined as window
function, so I guess this is the problem, and it's working in FF not by standard.
But is there another way to do that? I am not using jQuery, and I'd rather not.
The scrollIntoView method: The scrollIntoView() is used to scroll to the specified element in the browser. Example: Using scrollIntoView() to scroll to an element.
scrollTop = posArray[1]; Again, this will scroll the div so that the element you wish to see is exactly at the top (or if that's not possible, scrolled as far down as it can so it's visible).
It is not same as scrollTo behavior. It means scrollBy always scrolls up or down further from current position. Or you can say scrollBy scrolls by distance from current pixels. Or you can say scrollBy consider current position as (0,0) and scroll further.
scrollBy() method scrolls the document in the window by the given amount.
You can try this:
function scrollDiv(){
document.getElementById("d").scrollTop += 100;
document.getElementById("d").scrollLeft += 100;
}
Rather than do
function scrollDiv(){
document.getElementById("d").scrollTop += 100;
document.getElementById("d").scrollLeft += 100;
}
would you not do
document.getElementById("d").scrollBy({
top: 100,
left: 100,
behaviour: 'smooth'
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With