简体   繁体   中英

Detect Left Scroll JavaScript

What code would I add to trigger a block of code when the div is being scrolled left?

<script>
(function () {
    function scrollH(e) {
        e = window.event || e;
        var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
        document.getElementById('myDiv').scrollLeft -= (delta * 40);
        e.preventDefault();
    }
    if (window.addEventListener) {
        window.addEventListener("mousewheel", scrollH, false);
        window.addEventListener("DOMMouseScroll", scrollH, false);
    } else {
        window.attachEvent("onmousewheel", scrollH);
    }
    if "scrollingLeft" {
        // do something
    }
    else
    {
        // do something else
    }
})();
</script>

So far I have tried the following to no avail:

var isleft = e.delta < 0;
if isleft = true { do something }

As stated here You can handle horizontal scrolling by :

$("#someContainer").on("scroll", function (e) {
    horizontal = e.currentTarget.scrollLeft;
    vertical = e.currentTarget.scrollTop;
});

In this case this bind all kind of scroll events on this element so you can also handle

Vertical by e.currentTarget.scrollTop

and

Horizontal by e.currentTarget.scrollLeft

This solution will detect the DOM event. The div doesn't need to have some scrolling bars

You should be able to detect the scroll direction with this snippet :

$(window).on('DOMMouseScroll mousewheel', function (e) {
  if(e.originalEvent.detail > 0 || e.originalEvent.wheelDeltaX < 0) { //alternative options for wheelData: wheelDeltaX & wheelDeltaY
    //scroll right
    console.log("RIGHT");
  } else {
    //scroll left
    console.log("LEFT");
  }

  //prevent page fom scrolling
  return false;
});

It should work with all browsers. If you need to detect horizontal direction, replace wheelDeltaX with wheelDeltaY

If you want to detect the scroll direction and let the page scroll, return true at the end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM