Skip to content

Instantly share code, notes, and snippets.

@OwenMelbz
Created July 16, 2015 14:59
Show Gist options
  • Save OwenMelbz/e8510f94ebf8c169ae1e to your computer and use it in GitHub Desktop.
Save OwenMelbz/e8510f94ebf8c169ae1e to your computer and use it in GitHub Desktop.
Scroll Down to Sections
<div data-tag="{name:'home'}"></div>
<div data-tag="{name:'sec1'}"></div>
<div class="well-big" data-tag="{name:'sec2'}"></div>
<div class="big" data-tag="{name:'sec3'}"></div>
<div data-tag="{name:'sec4'}"></div>
<div data-tag="{name:'sec5'}"></div>
$(function() {
var sections = $('[data-tag]'),
activeSection = null,
getNextSection = function() {
var coords = [],
top = $(window).scrollTop();
_.each(sections, function(s) {
coords.push({
top: $(s).offset().top,
el: $(s),
tag: $(s).data('tag'),
height: $(s).outerHeight()
});
});
coords = _.sortBy(coords, 'top');
possible = _.filter(coords, function(e) {
return e.top > top;
});
possible.length && console.log(possible[0].tag);
return possible.length ? possible[0] : null;
},
nextSection = getNextSection(),
handleScroll = function(event) {
activeSection = nextSection;
nextSection = getNextSection();
if (nextSection) {
dir = event.originalEvent.wheelDelta || -event.originalEvent.detail;
if (dir < 0) {
if (activeSection && activeSection.height > $(window).innerHeight()) {
bottomPos = $(window).scrollTop() + $(window).innerHeight();
if (nextSection.top < bottomPos) {
$('html, body').stop().animate({
scrollTop: nextSection.top + 1,
}, 1000, 'easeOutExpo');
return false;
}
} else {
$('html, body').stop().animate({
scrollTop: nextSection.top + 1,
}, 1000, 'easeOutExpo');
return false;
}
}
}
};
$(document).on('mousewheel DOMMouseScroll', _.throttle(handleScroll, 500));
});
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>

Scroll Down to Sections

Allows you to scroll down to sections of multiple heights within your page - it will autoscroll down to the next section, if the area is larger than the screen it will let you continue scrolling normally until the next area is ready, it then lets you scroll back up naturally.

A Pen by Owen Melbourne on CodePen.

License.

* {
margin: 0; padding: 0;
}
div:nth-child(even){
background: red;
height: 100vh;
}
div:nth-child(odd){
background: green;
min-height: 100px;
}
.big {
height: 500px;
}
.well-big {
height: 1000px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment