Home > Software engineering >  Scroll to next div issue when the same class isn't continually repeated
Scroll to next div issue when the same class isn't continually repeated

Time:06-04

Having some issues creating a button used to scroll to next element of same class when there is HTML between the divs. The button is a "Next post" button and working nicely when the posts are set up like this.

<div >Content</div>
<div >Content</div>
<div >Content</div>

When there is some HTML between the first post and the rest it stops working.

<div >Content</div>
<div >Content</div>
<div >Content</div>
<div >Content</div>

The button is created successfully with jQuery but stops working when the post div isn't together continually after each other.

<div >
<a id="down">Next post</a>
</div>

<script>
var $currentElement = $(".new").first();

$("#down").click(function () {
    var currentElement = $currentElement.next(".new");
    // Check if next element actually exists
    if(currentElement.length) {
        // If yes, update:
        // 1. $currentElement
        // 2. Scroll position
        $currentElement = currentElement;
    } else {
        $currentElement = currentElement = $(".new").first();
    }
    
    $('html, body').stop(true).animate({
        scrollTop: $(currentElement).offset().top- $('.sticky').height()
    }, 0);
    return false;
});

</script>

I have tried making the next post button successfully using other jQuery solutions, but also seems stops working when there is something between the post divs.

<script>
$(".buttondiv").click(function() {
  var $target = $('.new').next('.p');
  if ($target.length == 0)
    $target = $('.new');
    
  $('html, body').animate({
    scrollTop: $target.offset().top
  }, 'slow');

  $('.active').removeClass('active');
  $target.addClass('active');
});

</script>

Any suggestions how to work around this issue?

CodePudding user response:

Change next('.new') to nextAll('.new').

next() only returns the next immediate sibling. In this case it checks <div >Content</div> for a new class and and doesn't find it so returns nothing.

nextAll() searches through all following siblings.

  • Related