Reputation: 383
I have created a function that animates a smooth scroll in vanilla Javascript so that the scroll behaviour can be experianced on all browsers.
I have two div's that I want to scroll simultaneously but running the function smoothScroll for both div1 and div2 in the provided snippet results in only the second div scrolling.
Question
Is it possible to run the function in a way that results in the divs scrolling at the same time?
Any help much appreciated and let me know if I you need any clarification.
function smoothScroll(id, scroll, duration)
{
let startTime = null;
animation = (currentTime) =>
{
if(startTime === null) startTime = currentTime;
const timeElapsed = currentTime - startTime;
var run = ease(timeElapsed, 0, scroll, duration);
document.getElementById(id).scrollLeft = run;
if(timeElapsed < duration) requestAnimationFrame(animation);
}
ease = (t, b, c, d) =>
{
t /= d/2;
if (t < 1) return c/2*t*t + b;
t--;
return -c/2 * (t*(t-2) - 1) + b;
}
requestAnimationFrame(animation);
}
smoothScroll('div1', 100, 1000);
smoothScroll('div2', 50, 1000);
div{
border: solid black 1px;
display: flex;
width: 150px;
overflow: auto;
margin: 1rem;
}
<div id="div1">
<h1>Hello world!...................................................</h1>
</div>
<div id="div2">
<h1>Hello world!...................................................</h1>
</div>
Upvotes: 0
Views: 44
Reputation: 198324
Your variables are leaking out of scope: both animation
and ease
were used as global variables.
function smoothScroll(id, scroll, duration)
{
let startTime = null;
const ease = (t, b, c, d) =>
{
t /= d/2;
if (t < 1) return c/2*t*t + b;
t--;
return -c/2 * (t*(t-2) - 1) + b;
}
const animation = (currentTime) =>
{
if(startTime === null) startTime = currentTime;
const timeElapsed = currentTime - startTime;
var run = ease(timeElapsed, 0, scroll, duration);
document.getElementById(id).scrollLeft = run;
if(timeElapsed < duration)
requestAnimationFrame(animation);
}
requestAnimationFrame(animation);
}
smoothScroll('div1', 100, 1000);
smoothScroll('div2', 50, 1000);
div{
border: solid black 1px;
display: flex;
width: 150px;
overflow: auto;
margin: 1rem;
}
<div id="div1">
<h1>Hello world!...................................................</h1>
</div>
<div id="div2">
<h1>Hello world!...................................................</h1>
</div>
Upvotes: 6