Sonic Hedgehog
Sonic Hedgehog

Reputation: 3

JavaScript mousewheel event to scroll page horizontally when vertical scroll

I am trying to detect when a user scrolls up or down on an fixed height element and update the element's transform: translateX CSS value accordingly to scroll the contents either to the left or two the right. However, I can't figure out how to get the proper value from the delta.

document.getElementById("list").addEventListener("wheel", myFunction);

function myFunction(event) {
  var matrix = $('.gallery-list').css('transform').split(/[()]/)[1];

  var y = parseInt(event.deltaY);
  var posX = parseInt(matrix.split(',')[4]);

  console.log(y);
  console.log(posX);
  console.log(y + posX);

  //$('.gallery-list').css('transform', 'translateX('+posX + y+'px)');
}

Here is a Codepen here: https://codepen.io/kylehagler/pen/OKxMGr

Upvotes: 0

Views: 527

Answers (1)

Josh H
Josh H

Reputation: 274

Add this to your css:

.outside {
  width: 100vw;
  height: 100vh;
  top: 0;
  left: 0;
  position: absolute;
}

Surround the gallery-list div with:

<div id="outside" class="outside">

Finally, here is the JS:

document.getElementById("outside").addEventListener("wheel", myFunction);

var total = 0;

function myFunction(event) {
  var y = parseInt(event.deltaY);
  
  total += y;
  
  $(".gallery-list").css('transform', 'translateX(' + total + 'px)');
}

Upvotes: 1

Related Questions