javascripthtmljquerycursormouse

MouseWheel Doesn't Scroll Back and Forth


I'm using this script for mousewheel. What I have tried only works one way. Instead of scroll up and down it just Scrolls forward. What I want it to do is change the cursor Forwards and Backwards. Here is what I have tried.

I've also tried the DeltaY method, But could not figure it out.

var clicked = 0;
window.addEventListener('wheel', function(event) {
  if (clicked == 0) {
    document.getElementsByTagName("body")[0].style.cursor = "url('https://tim-school.com/codepen/mouser/1.png'), auto";
    clicked = 1;
  } else if (clicked == 1) {
    document.getElementsByTagName("body")[0].style.cursor = "url('https://tim-school.com/codepen/mouser/2.png'), auto";
    clicked = 2;
  } else if (clicked == 2) {
    document.getElementsByTagName("body")[0].style.cursor = "url('https://tim-school.com/codepen/mouser/3.png'), auto";
    clicked = 3;
  } else if (clicked == 3) {
    document.getElementsByTagName("body")[0].style.cursor = "url('https://tim-school.com/codepen/mouser/4.png'), auto";
    clicked = 4;
  } else if (clicked == 4) {
    document.getElementsByTagName("body")[0].style.cursor = "url('https://tim-school.com/codepen/mouser/5.png'), auto";
    clicked = 5;
  } else if (clicked == 5) {
    document.getElementsByTagName("body")[0].style.cursor = "url('https://tim-school.com/codepen/mouser/6.png'), auto";
    clicked = 0;
  }
});
body {
  background-color: #ffffff;
  overflow: hidden;
}

html,
body {
  height: 100%;
}

.box {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
<div class="box"></div>


Solution

  • Using event.deltaY will indicate if you should increment or decrement clicked. If you limit clicked to 1 through 6 then you can use a it in a template string to create the url string.

    In the example below I moved the setting of .style.cursor to a separate function so you can make a call to set the initial cursor without waiting for the wheel.

    // EDIT changed to 1
    var clicked = 1;
    
    setCursor( )
    
    window.addEventListener('wheel', function (event) {
      // EDIT Increment or decrement clicked based on wheel movement direction
      if( event.deltaY < 0 ) {
        if( --clicked < 1 )  clicked = 6
      }
      else {
        if( ++clicked > 6 )  clicked = 1
      }
    
      setCursor( )
    });
    
    function setCursor( ) {
      // EDIT Used clicked in string template to set/change filename
      document.getElementsByTagName("body")[0].style.cursor =
        `url('https://tim-school.com/codepen/mouser/${clicked}.png'), auto`;
    }
    body {
      background-color: #ffffff;
      overflow: hidden;
    }
    
    html,
    body {
      height: 100%;
    }
    
    .box {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
    }
    <div class="box"></div>