Search code examples
javascriptjqueryhtmlslide

How can I slide to the next element per click?


I am trying to make post navigation. Click the "next post" button, and slide the window to the #post-n element. But post numbers are random, not hierarchical. I can make the first slide, but can't make the other slides.

$('.next-post').click(function(e) {
    e.preventDefault();

    $([document.documentElement, document.body]).animate({
        scrollTop: $("#post-2").offset().top
    }, 500);

});
.post {
  display: block;
  height: 500px;
  width: 500px;
  background-color: #2196F3;
  margin-bottom: 30px;
}

.next-post {
  position: fixed;
  background-color: #f44336;
  color: #fff;
  padding: 5px;
  text-decoration: none;
  border-radius: 5px;
  bottom: 15px;
  left: 50%;
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<article id="post-1" class="post"></article>
<article id="post-2" class="post"></article>
<article id="post-3" class="post"></article>
<article id="post-4" class="post"></article>
<article id="post-5" class="post"></article>
<article id="post-6" class="post"></article>

<a href="#" class="next-post">Next Post</a>

Here is the JSFiddle: https://jsfiddle.net/xpvt214o/514002/


Solution

  • I tracked the current post index and all queried posts as vars, then incremented the index on click and selected that index from that global var:

    var currentPostIndex = 0;
    var allPosts = $(".post");
    
    $('.next-post').click(function(e) {
        e.preventDefault();
    
        currentPostIndex++;
        $([document.documentElement, document.body]).animate({
            scrollTop: $(allPosts[currentPostIndex]).offset().top
        }, 500);
    });
    

    https://jsfiddle.net/35w9ze2s/5/