Im relatively new to JS coding, and can’t get this little number to work. Can anyone tell me what I’m doing wrong?
My JavaScript is:
incrementScroll = function() {
window.scrollBy(0, 3) ;
}
startScrollLoop = function() {
scrollLoopId = setInterval( "incrementScroll", 5) ;
}
stopScrollLoop = function() {
clearInterval( scrollLoopId ) ;
}
And my HTML is:
<button onclick="startScrollLoop()">AUTO SCROLL</button>
<button onclick="stopScrollLoop ()">STOP SCROLL</button>
Again, many thanks for help. New to all of this and need to make a project work by morning.
Cheers.
The first argument to
setInterval()should be a function reference, or non-ideally, a string to be eval()’d, which would be a complete function call with(). So remove the quotes:And to clear the scroll, you will need to define
scrollLoopIdat a higher scope withvar.Jsfiddle demo
(uses a slower scroll speed to give you a chance to click the stop button in the middle of the text)
Note that it is good practice to use the
varkeyword with each of these. even though they would end up atwindowscope anyway (assuming they’re not being defined inside another function).