Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Scroll to next div issue when the same class isn't continually repeated

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 class="new">Content</div>
<div class="new">Content</div>
<div class="new">Content</div>

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

<div class="new">Content</div>
<div class="something-else">Content</div>
<div class="new">Content</div>
<div class="new">Content</div>

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div class="buttondiv">
<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?

>Solution :

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

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

nextAll() searches through all following siblings.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading