Home > other >  Scroll to Next Section jquery
Scroll to Next Section jquery

Time:08-17

    (function ($) {
  var window = $(window),
    one = $("#one"),
    two = $("#two"),
    three = $("#three"),
    four = $("#four"),
    oneT = one.offset().top,
    twoT = two.offset().top,
    threeT = three.offset().top,
    fourT = four.offset().top;

  function Scroll(div) {
    var tp = $(div).offset().top;
    $("html, body").animate({ scrollTop: tp }, 500);
  }

  var tmp = 0;
  var mousewheelevt = /Firefox/i.test(navigator.userAgent)
    ? "DOMMouseScroll"
    : "mousewheel";

  $("section").bind(mousewheelevt, function (e) {
    var evt = window.event || e;
    evt = evt.originalEvent ? evt.originalEvent : evt;
    var delta = evt.detail ? evt.detail * -40 : evt.wheelDelta;

    console.log(delta);
    if (delta < 0) {
      tmp  ;
      if (tmp > 0) {
        var divT = $(this).next();
        Scroll(divT);
        tmp = 0;
      }
    } else if (delta > 0) {
      tmp--;
      console.log("going up");
      if (tmp < -1) {
        var divT = $(this).prev();
        Scroll(divT);
        tmp = 0;
      }
    }
  });
})(jQuery);

This is the code im using is there any problem , i am getting error called

index.html:100 Uncaught TypeError: Cannot read properties of undefined (reading 'top')

Can you please help me with this.

CodePudding user response:

You likely do not have 4 sections in your HTML or you have divs with a class and you need a dot: $(".section")

Then you need to use the wheel event instead of your current deprecated code

jQuery messes things up and you need to then use the originalEvent

You do not actually use any of the vars you declared in the beginning

I also got rid of half the tests by testing the existence of next/prev

(function($) {
  function Scroll($div) {
    var tp = $div.offset().top;
    $("html, body").animate({
      scrollTop: tp
    }, 500);
  }

  const $sections = $("section");
  $sections.on("wheel", function(e) {
    const delta = e.originalEvent.wheelDelta; // all newer browsers
    const down = delta < 0;
    let $divT = down ? $(this).next("section") : $(this).prev("section");
    // we may get a next or previous that is undefined - not obvious
    if (!$divT.attr("id") || $divT.length === 0) {
      if (down) $divT = $sections.first();
      else $divT = $sections.last();
    }
    Scroll($divT);
  });
})(jQuery);
section {
  height: 500px;
  border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<section id="one">One</section>
<section id="two">Two</section>
<section id="three">Three</section>
<section id="four">Four</section>

  • Related