Rich Walker
Rich Walker

Reputation: 33

JS next tab jump section

I have a simple next and previous tab to move between "section". When you click the next tab the page moved down and skips the next "section" and goes the one after.

    var $sec = $("section");
$(".prev, .next").click(function() {
  var y = $sec.filter(function(i, el) {
    return el.getBoundingClientRect().top > 0;
  })[$(this).hasClass("next") ? "next" : "prev"]("section").offset().top;
  $("html, body").stop().animate({
    scrollTop: y
  });
});
      <div data-role="page" id="main">
        <section>
            <div id="home-section" class="section">
                <img src="images/welcome-homepage.jpg" />
            </div>
        </section>
        <section>
            <div id="about-section" class="section">
                <img src="images/about-us.jpg" />
            </div>
        </section>
        <section>
            <div id="service-charter-section" class="section">
                <img src="images/service-charter.jpg" />
            </div>
        </section>
        <section>
            <div id="testionials-section" class="section">
                <img src="images/about-us.jpg" />
            </div>
        </section>
    </div>

Upvotes: 0

Views: 131

Answers (1)

Bryan
Bryan

Reputation: 1005

This should work. It does not account for current scroll position, i.e. if you scroll halfway down and hit next, it will continue in series from the last item clicked through. It just makes an array of all sections positions and hops through that as you click prev / next.

jQuery(document).ready(function($) {
  var sectionPosition = 0;
  var scrollPositions = []

  function scroll(y) {
    $('html').stop().animate({
      scrollTop: y
    });
  }

  $("section").each(function(i, el) {
    scrollPositions.push(parseInt($(el).offset()['top']))
  })

  $(".prev, .next").click(function() {
    if ($(this).hasClass('next')) {
      scroll(scrollPositions[sectionPosition + 1]);
      if (sectionPosition < scrollPositions.length) {
        sectionPosition++;
      }
    } else if (sectionPosition > 0) {
      scroll(scrollPositions[sectionPosition - 1]);
      sectionPosition--;
    }
  });
});

Upvotes: 1

Related Questions