Reputation: 41
I built a menu with anchor links to sections.
For each section, I have animation to appear on scroll (opacity, translate, scale change). I use the AOS animation library (https://github.com/michalsnik/aos).
My target is to scroll to the correct position of the clicked link (anchor).
My code example: https://codepen.io/matteokrr/pen/VwqKxbL
JS code:
$(document).on('click', 'a[href^="#"]', function (e) {
e.preventDefault();
var target = $(this.hash);
if (target.length) {
$('html, body').stop().animate({
scrollTop: target.offset().top
}, 2000, 'swing');
}
});
CSS animation:
[data-aos='zoom-in-down'] {
transform: translate3d(0, -200px, 0) scale(.6);
}
The problem:
When the targeted section is not visible yet, then the offset top position of the section is wrong.
How can I fix that?
Upvotes: 0
Views: 390
Reputation: 136
You can manipulate the animation process in jquery (https://api.jquery.com/animate/#animate-properties-options).
Try this out:
$('html, body').stop().animate({
scrollTop: target.offset().top
}, {
duration: 2000,
easing: 'swing',
step: function (now, tween) {
if (tween.end !== target.offset().top) {
tween.end = target.offset().top
}
}
});
Upvotes: 1