javascript - Adding scroll speed to function -
i have following code. how use setinterval or settimeout make jump 0px 500px happen in 3000ms?
<!doctype html> <html> <head> <style> body { width: 5000px; } </style> </head> <body> <p>click button scroll document window 500 pixels horizontally.</p> <button onclick="scrollwin()">click me scroll horizontally!</button><br> <br> <script> function scrollwin() { window.scrollto(500, 0); } </script> </body> </html>
here's 1 way - divide number of pixels move amount of time move in. use setinterval
move number of pixels in fixed length of time inervaltime
. then, cancel interval when scroll position reaches target.
function scrollwin(target, time) { var currentposition = window.pagexoffset || document.documentelement.scrollleft; var scrollinterval = target / time; var intervaltime = 10; var intervalfunction; intervalfunction = setinterval(function() { currentposition = currentposition + scrollinterval * intervaltime; window.scrollto(currentposition, 0); if (currentposition >= target) { window.clearinterval(intervalfunction); } }, intervaltime) }
body { width: 5000px; }
<p>click button scroll document window 500 pixels horizontally.</p> <button onclick="scrollwin(500, 3000)">click me scroll horizontally!</button>
Comments
Post a Comment