I make use of the code below to scroll to the next section of a page on the click of an arrow:
$(function() {
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500, 'easeOutExpo');
event.preventDefault();
});
});
and this is the html:
<!-- My Story Intro -->
<section class="intro scroll-to-section" id="my-story-intro">
<div class="intro-body">
<div class="container">
<div class="row">
<div class="col-md-12">
<a href="#my-story" class="btn page-scroll">
<i class="fa fa-angle-down animated"></i>
</a>
</div>
</div>
</div>
</div>
</section> <!-- / #my-story-intro -->
<!-- My story-->
<section id="my-story" class="content-section normal-scroll-to-section">
<div class="container">
What I am trying to achieve now is exactly the same effect but on mouse scroll.
So I would scroll down and the scroll would animate to the next section as it does on the click of the arrow on the code above.
Also I would like the scroll to animate to the top of the very first section when on the second section and scrolling up.
I have trying many plugins but they haven't really worked. And a plugin might seem unnecessary for what I am looking for.
I am not hoping anyone will just do the code for me. By coming here my hope was to get some valuable feedback that can hopefully point me in the right direction to implement the desired functionality.
EDIT
I came across a bit of code that actually does what I want but unfortunately it does not work well on OS. After testing on a mac the snapping does not work as on windows and it just stops randomly in the middle of the sections. Why would this be? Code below:
$(function() {
var delay = false;
$(document).on('mousewheel DOMMouseScroll', function(event) {
if(delay) return;
delay = true;
setTimeout(function(){delay = false},200);
var wd = event.originalEvent.wheelDelta || -event.originalEvent.detail;
var a = document.getElementsByClassName("scroll-to");
if(wd < 0) {
for(var i = 0 ; i < a.length ; i++) {
var t = a[i].getClientRects()[0].top;
if(t >= 40) break;
}
}
else {
for(var i = a.length-1 ; i >= 0 ; i--) {
var t = a[i].getClientRects()[0].top;
if(t < -20) break;
}
}
$('html, body').stop().animate({
scrollTop: a[i].offsetTop
}, 1500, 'easeOutExpo');
event.preventDefault();
});
});