JQuery / JS : Detect user's scroll attempt without any window overflow to scroll to

心已入冬 提交于 2019-11-30 19:26:21
TreeTree

Have a look at this question. I used it as a reference to make this fiddle.

Works only in Firefox:

$('html').on ('DOMMouseScroll', function (e) {
    var delta = e.originalEvent.detail;

    if (delta < 0) {
        $('p').text ('You scrolled up');
    } else if (delta > 0) {
        $('p').text ('You scrolled down');
    }

});

Works in Chrome, IE, Opera and Safari:

$('html').on ('mousewheel', function (e) {
    var delta = e.originalEvent.wheelDelta;

    if (delta < 0) {
        $('p').text ('You scrolled down');
    } else if (delta > 0) {
        $('p').text ('You scrolled up');
    }
});

You'd have to bind it on an element that spans your entire browser screen.

The answer from TreeTree can be simplified into one function that supports all browsers. Combine the mousewheel and DOMMouseScroll events since jQuery supports one or more event parameter(s). However, my testing showed on() did not work in the latest Firefox. Use bind() instead. You can also combine the var delta declaration to support all browsers:

$('html').bind('mousewheel DOMMouseScroll', function (e) {
    var delta = (e.originalEvent.wheelDelta || -e.originalEvent.detail);

    if (delta < 0) {
        console.log('You scrolled down');
    } else if (delta > 0) {
        console.log('You scrolled up');
    }
});

The modern solution relies on the wheel event (IE9+)

$('selector').on('wheel', function(event) {
  var delta = {
    x: event.originalEvent.deltaX, 
    y: event.originalEvent.deltaY
  };

  if (delta.x != 0 || delta.y != 0) {
    //user scrolled
  }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!