Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: scrollBy function executed on a div

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.

like image 457
Jeni Avatar asked Mar 12 '15 14:03

Jeni


People also ask

How do I scroll to a specific div?

The scrollIntoView method: The scrollIntoView() is used to scroll to the specified element in the browser. Example: Using scrollIntoView() to scroll to an element.

How do I scroll to an element within an overflowed div?

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).

What is difference between scrollTo and scrollBy?

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.

What does scrollBy do?

scrollBy() method scrolls the document in the window by the given amount.


2 Answers

You can try this:

function scrollDiv(){
    document.getElementById("d").scrollTop += 100;
    document.getElementById("d").scrollLeft += 100;
}
like image 100
Pavel Avatar answered Oct 07 '22 19:10

Pavel


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'
})
like image 30
Andy Wilson Avatar answered Oct 07 '22 18:10

Andy Wilson