I'm trying to change the href of a "next" button so that clicking it will continually move the user down the blog page to the next anchor. Since the user can scroll down without using the next button, the href needs to change whenever an anchor is scrolled past. The button is positioned fixed relative to the window and thus stays visible.
What's frustrating is that I receive an inconsistent result - the first time down the page, the link updates to #post-1 and #post-2, but post-2 does not seem to update the href to #post-3. Then post-3 updates the href to #post-4 (which doesn't exist but that's beside the point for the moment.) But then when scrolling back up from the bottom, post-2 suddenly works while others don't. Here's my relevant code:
HTML:
<span id="post-0" class="anchor"></span>
<div class="row blog-page">
<a href="#post-1" id="blog-next">
<i class="blog-arrow fa fa-chevron-down"></i>
</a>
</div>
<span id="post-1" class="anchor"></span>
<div class="row blog-page">
<h3>header</h3>
</div>
<span id="post-2" class="anchor"></span>
<div class="row blog-page">
<h3>header</h3>
</div>
<span id="post-3" class="anchor"></span>
<div class="row blog-page">
<h3>header</h3>
</div>
JS:
<script type="text/javascript">
$(document).ready(function(){
$(function () {
var nextHash = 0;
$(document).scroll(function () {
$('.anchor').each(function () {
var top = window.scrollY;
var distance = top - $(this).offset().top;
var hash = parseInt($(this).attr('id').slice(5));
if (distance < 30 && distance > -30 && nextHash != hash) {
nextHash = hash + 1;
document.getElementById('blog-next').setAttribute('href', '#post-' + nextHash);
}
});
});
});
});
</script>
You can see my live code here (it's the down arrow in the bottom right corner): www.zaplings.com/blog
Thank you for your help.