Home > Net >  how to go to(instead of scrolling to) the next anchor using the mouse wheel?
how to go to(instead of scrolling to) the next anchor using the mouse wheel?

Time:09-20

i am making a website where i would like the screen to go to the other one(each one is an anchor) when the user uses the mouse wheel, i found a code here on stack-overflow that works great, but it scrolls to the other screen instead of "teleporting" to the other one. since the code is using jquery and i dont understand a thing of it or how this code works, i would like some help to make it teleport to the other screen.

this is the code i got from stack-overflow:

(function() {
    var delay = false;
  
    $(document).on('mousewheel DOMMouseScroll', function(event) {
      event.preventDefault();
      if(delay) return;
  
      delay = true;
      setTimeout(function(){delay = false},200)
  
      var wd = event.originalEvent.wheelDelta || -event.originalEvent.detail;
  
      var a= document.getElementsByTagName('a');
      if(wd < 0) {
        for(var i = 0 ; i < a.length ; i  ) {
          var t = a[i].getClientRects()[0].top;
          if(t >= 40) break;
        }
      }
      else {
        for(var i = a.length-1 ; i >= 0 ; i--) {
          var t = a[i].getClientRects()[0].top;
          if(t < -20) break;
        }
      }
      
      if(i >= 0 && i < a.length) {
        $('html,body').animate({
          scrollTop: a[i].offsetTop
        });
      }
    });
  })();
  console.clear();

CodePudding user response:

Here is a newer version using vanilla JS

The scroll itself needs some tweaking depending on your CSS

window.addEventListener("DOMContentLoaded", () => {
  const a = document.querySelectorAll('a');
  let idx = 0;
  let delay = false;
  const goto = e => {
    e.preventDefault();
    if (delay) return;
    delay = true;
    setTimeout(function() {
      delay = false
    }, 200); // debounce

    const up = e.deltaY < 0;

    if (up) {
      idx--;
      if (idx < 0) idx = 0;
    } else {
      idx  ;
      if (idx >= a.length) idx = a.length - 1;
    }
    a[idx].scrollIntoView();
  };


  document.addEventListener('wheel', goto);
});
div {
  height: 500px;
  border: 1px solid black;
  background-color: yellow;
  vertical-align: top;
}
<div>
  <a id="one">One</a>
</div>
<div>
  <a id="two">Two</a>
</div>
<div>
  <a id="three">Three</a>
</div>

CodePudding user response:

You have an animation for the scrollTop property (it will animate to the value), you need to just set the value.

Try changing .animate to .css https://api.jquery.com/css/#css-properties

      if(i >= 0 && i < a.length) {
        $('html,body').css({
          scrollTop: a[i].offsetTop
        });
      }
  • Related