I am facing a challenge where before scroll, you will notice when scrolling down or up, there is a slight pixel shift in the same direction before a smooth scroll animation occurs and snaps to the next or previous section depending on the scroll direction.
Code can be found here: https://stackblitz.com/edit/html-sample-rpcn3b?file=index.html
Preview can be found here: https://html-sample-rpcn3b.stackblitz.io
How can I remove this slight shift before the animated scroll happens, so that I can get a smooth scroll snapping from one section to the next. In the end (for the targeted sections) I want to achieve a smooth scroll closely similar to this example here with swiperjs: https://swiper-master.webflow.io/full-page-vertical
2
Answers
Your code seems to work as expected if you tweak a bit
wtd
andst
ingetClosestElement
(see myHERE
comments in the snippet below).Moreover, some of your HTML tags are not closed. See
<div class="container-large">
.EDIT 1
After reading your comment, it seems that I misunderstood the meaning of your question…
In fact, except if your challenge is to reinvent the wheel, you may want to use a small library like jQuery Easing Plugin. You will find below the same example with a custom easing function and no
delay
:It looks much smoother now!
For the record, you might also want to use CSS instead of JS:
It does not work very well on IE, though. This browser is just too old.
EDIT 2
If you want something even smoother, I am not sure you need
.animate()
. I removed it from the code. Of course, the jQuery Easing Plugin is not necessary anymore.Besides, even though it is not compulsory, I recommend you to implement throttling to increase performance (the scroll event fires way too often for what we need to do). The easiest strategy here is to use
_.throttle()
from Lodash.You can achieve a smooth scroll snap experience with just pure CSS by using
scroll-snap-type
property, without jQuery or js.refer:
https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-snap-type
note: check web browser compatibility
for your case, if you need to enable smooth scroll snap only at the bottom part, the
section
tags, you may just do as below: (add this style and remove other js animation)*do
scroll-snap-type: y mandatory
for parent element andscroll-snap-align: center
for child element that need scroll snap , no complicated js animation needed.