AngularJS -horizontal scroll with mousewheel

by Jens Kühn

HTML

<div ng-app="myApp">


  <div>
    <div class="prt" horizontal-scroll>
        <div class="child">1111111</div>
        <div class="child">2222222222222</div>
        <div class="child">333</div>
        <div class="child">444</div>
        <div class="child">555</div>
    </div>
  </div>
</div>

CSS

div.prt {
  display: flex;
  flex-direction: row;
  width: 200px;
  height: 200px;
  border: 1px solid orange;
  overflow: hidden;
}

.child {
  height: 100px;
  border: 2px dashed red;
  margin: 0 3px;
  align-self: center;
}

JavaScript

angular.
module('myApp', []).
directive('horizontalScroll', function() {

  return {
    link: function(scope, element, attrs) {
      var base = 0

      element.bind("DOMMouseScroll mousewheel onmousewheel", function(event) {

        // cross-browser wheel delta
        var event = window.event || event; // old IE support
        var delta = Math.max(-1, Math.min(1, (event.wheelDelta || -event.detail)));
        console.log('element:', element[0].children);
        
        var maxWidth = 0;
        for (var i=0; i < element[0].children.length; i++) {
        console.log(' element)[i]',  element[0].children[i], element[0].children[i].offsetWidth);
        	maxWidth += element[0].children[i].offsetWidth;
        }
        //maxWidth -= element[0].clientWidth;
        console.log('maxWidth', maxWidth,  element[0].clientWidth);

        scope.$apply(function() {
          base += 30 * delta;
          if( base < 1 ) {
            element.children().css({
              'transform': 'translateX(' + base + 'px)'
            });
          } else {
          	base = 30;
          }
          console.log('base: ',base);
          
        });

        // for IE
        event.returnValue = false;
        // for Chrome and Firefox
        if (event.preventDefault) {
          event.preventDefault();
        }


      });
    }
  };
});