简体   繁体   中英

JQuery Scroll to Next Section

Can someone please help?

I seem to have two issues:

  1. page isn't scrolling and
  2. when trigger-scroll clicked 3x, .top is undefined.

.hero-banner is a full screen slideshow. When .trigger-scroll is clicked, page needs to scroll to sections.scroll-here. When reached last section needs to scroll to top.

Thanks in advance for your answers.

HTML:

    <section class="hero-banner">full screen section</section>
    <div class="trigger-scroll"></div>
    <section class="scroll-here" id="first-section">some content</section>
    <section class="scroll-here" id="second-section">some content</section>
    <section class="scroll-here" id="third-section">some content</section>

JS:

            $(document).ready(function() {
              $('.page-scroller', function() {
                var $scrollSection = $('.scroll-here')
                var $scrollTrigger = $('.trigger-scroll')
                var nextSection = 0;

                $scrollTrigger.on( 'click', function() {
                  $(this).removeClass('go-to-top');

                  // If at last section, scroll back to top on next click:
                  if (nextSection >= $scrollSection.length) {
                    $('html, body').animate({ scrollTop: 0 }, 1000);
                    nextSection = 0;
                    return;
                  }

                  // If you've already scrolled down and then click button, run a check
                  // to find next section position so you don't go backwards:
                  while ( $('body').scrollTop() > $($scrollSection[nextSection]).offset().top ) {
                    nextSection++;
                  }

                  // If next section is the last, add class to rotate arrow graphic:
                  if (nextSection === ($scrollSection.length - 1)) {
                    $(this).addClass('go-to-top');
                  }

                  // Move to next section and increment counter check:
                  $( 'html, body' ).animate({ scrollTop: $($scrollSection[nextSection]).offset().top }, 1000);
                  nextSection++;
                });
              });
            });

After a few hours trying to figure out why <scrollTop> wasn't working, I found that <body> tag had a css style of <height:100%;> which was messing up the <offset> . Alex thanks for your help. For others, here is a working JSFiddle Link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM