I have a simple page where I am going to place a large form on the right side, and a navigation menu on the left allowing the user to jump to sections of the large form (this could also be used for large articles too - for now to mock the size I have added a large bottom padding with CSS). The right column has been styled to fit the height of the window using height: 100vh.
When clicking a link on the right and the section offsetTop
is greater than its parent's scrollTop
the scrolling is smooth. I use a JavaScript setTimeout
and I set the timeout's interval using a loop... this is great! However should I want to scroll up, that being the section's offsetTop is less than its parent's scrollTop
I get problems - it is janky, slow and doesn't really work... I have been looking at this for too long so if someone can help I'd be most appreciative. This is my JavaScript function
function scrollToAchor(where, event) {
event.stopPropagation();
var element = document.querySelector('.aims-form__form').querySelector('a[name="' + where + '"]');
var to = element.offsetTop - 30;
var from = document.querySelector('.aims-form__form').scrollTop
let timeOut = 0;
if(to >= from) {
for(let i = from; i <= to; i+=5) {
// this works and is great!!!
setTimeout(function () {
document.querySelector('.aims-form__form').scrollTop = i;
}, i/2);
}
} else {
for(let k = from; k >= to; k-=5) {
// I need to set the timeout Interval so the animation is smooth but it is really slow
// with the above setInterval above we are counting up... How do I get this smooth
timeOut = timeOut + (to + 15) / 2;
setTimeout(function () {
document.querySelector('.aims-form__form').scrollTop = i;
}, timeOut);
}
}
}
This shouldn't phase me but I can't get my head around it and now I have a mental block. To understand the scrolling function better here is the HTML, however to get a full picture (including the necessary CSS) here is a jsbin of the full thing https://jsbin.com/nidevaj/edit?html,css,js,output
<div class="aims-form">
<div class="aims-form__navigation">
<ul>
<li>
<a onClick="scrollToAchor('section1', event)" class="aims-form__anchor">Section 1</a>
</li>
<li>
<a onClick="scrollToAchor('section2', event)" class="aims-form__anchor">Section 2</a>
</li>
<li>
<a onClick="scrollToAchor('section3', event)" class="aims-form__anchor">Section 3</a>
</li>
<li>
<a onClick="scrollToAchor('section4', event)" class="aims-form__anchor">Section 4</a>
</li>
</ul>
</div>
<div class="aims-form__form">
<section>
<a name="section1"></a>
Section 1
<br>
... content lots of content
</section>
<section>
<a name="section2"></a>
Section 2
<br>
... content lots of content
</section>
<section>
<a name="section3"></a>
Section 3
<br>
... content lots of content
</section>
<section>
<a name="section4"></a>
Section 4
<br>
... content lots of content
</section>
</div>
</div>