0

I have a div that auto-scrolls from the left to right. I use jQuery to achieve that. In the jQuery callback function, I called the function that makes it auto-scrolls from the left to right. However, the callback function fails and it doesn't scroll from the left to right again. What am I doing wrong?

function scroll() {
 
    var element = document.getElementById("scroll");
    var width = element.scrollWidth;
 
    $(document).ready(function(){

 $("#scroll").animate({scrollLeft: width}, 5000, function(){ 
 scroll();
 });
    });
 
} //end of scroll() 
 
scroll();   
#scroll {
    display: inline-block;
    padding: .5%;
    border: 1px solid black;
    white-space: nowrap;
    width: 10%; 
    overflow-x: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "scroll">one two three four five six seven eight nine ten</div>
frosty
  • 2,559
  • 8
  • 37
  • 73

1 Answers1

1

I believe its due to "Maximum call stack size exceeded error"

Since you're calling scroll, which in turn calls scroll and so on, it hits the stack limit.

Refer this answer on how to use recursive function with a base case Maximum call stack size exceeded error

Update: It was due to the action of scrollLeft which had scrolled the element to left and needed to be scrolled back to 0 before invoked again.

Community
  • 1
  • 1
raghav
  • 285
  • 2
  • 12
  • Even if that is so, it should've scroll a few more times before exceeding itself. The example above only scrolled once. – frosty Oct 11 '15 at 00:49
  • Yea. Check this fiddle out. https://jsfiddle.net/mufum96L/2/ It was because the element had been scrolled to left already and need to be scrolled back to '0' before animated again – raghav Oct 11 '15 at 00:56
  • That fiddle is the same exact thing as my snippet! – frosty Oct 11 '15 at 00:57
  • It works. But why is there a slight pause before scrolling again? Is there a way to make the slight pause go away? – frosty Oct 11 '15 at 01:04
  • So nothing to do with "Maximum call stack size exceeded error" after all. – Shikkediel Oct 11 '15 at 01:08
  • @Shikkediel :) Exactly. – frosty Oct 11 '15 at 01:09
  • I'd take out the `$(document).ready()` by the way and wrap *all* the code in it. Without the onload event from jsfiddle, it's likely to fail in a live environment unless the script is placed at the bottom of the markup. And if that's the case, it's superfluous anyway. – Shikkediel Oct 11 '15 at 01:12