Skip to content

Instantly share code, notes, and snippets.

@clayb
Last active April 28, 2016 21:08
Show Gist options
  • Save clayb/76b0b64b6d66deea5596 to your computer and use it in GitHub Desktop.
Save clayb/76b0b64b6d66deea5596 to your computer and use it in GitHub Desktop.
Scroll to Next or Previous <article> element
/**document ready**/
$(document).ready(function () {
/** scroll to element function **/
function scrollToElement(selector, time, verticalOffset) {
time = typeof (time) != 'undefined' ? time : 500;
verticalOffset = typeof (verticalOffset) != 'undefined' ? verticalOffset : 0;
element = $(selector);
offset = element.offset();
offsetTop = offset.top + verticalOffset;
$('html, body').animate({
scrollTop: offsetTop
}, time);
}
count = 0;
var max_length = $('article').length;
/* scroll to 150px before article with animation time of 1000ms */
$('#next').click(function (e) {
if (count < max_length) {
count++;
} else {
count = 1;
}
e.preventDefault();
scrollToElement('article:nth-child(' + count + ')', 1000, -150);
});
$('#prev').click(function (e) {
if (count > 1) {
count--;
} else {
count = max_length;
}
e.preventDefault();
scrollToElement('article:nth-child(' + count + ')', 1000, -150);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment