0

I need to reimplement the scroll functionality over an overflow area, so that the mousewheel changes the current selection rather than the scroll position.

To do this at the very least, I need to block the default scroll action of the browser. From what I can tell knockout does this by default, provided that you don't return 'true' from the event handler.

However it doesn't seem to work, nor does calling 'preventDefault' on the event explicitly. This problem must be specific to the scroll event.

scrolled: function (vm, event) {
    event.preventDefault();
    return false;
}

Example: http://jsfiddle.net/vjLqauq5/2/

Daniel Revell
  • 7,762
  • 14
  • 51
  • 90
  • 1
    http://stackoverflow.com/a/15479625/2182767 - check this answer – Andrey Aug 10 '15 at 10:22
  • This is using a jquery pluggin and just wrapping initalisation within a knockout binding. A possible solution, but what I'm really after is I can't block the event where I am. – Daniel Revell Aug 10 '15 at 10:33
  • http://stackoverflow.com/a/4770179/10756 - indicates that the scroll itelf event cannot be cancelled. This must mean that neither ko or jquery are at fault here. – Daniel Revell Aug 10 '15 at 10:43

1 Answers1

7

Hat tip to Andrey for pointing out that you should use the mousewheel event rather than the scroll event.

<div class="container" data-bind="foreach: items, event: { mousewheel: scrolled }">

From the mousewheel event, deltaY will give you the scroll direction, which you can use to change which item is selected:

scrolled: function (vm, event) {
    var direction = Math.sign(event.deltaY), // 1 is down, -1 is up
        maxIdx = vm.items().length - 1,
        selectedIdx = vm.items.indexOf(vm.selected()) + direction;
    if (selectedIdx >= 0 && selectedIdx <= maxIdx) {
        vm.selected(vm.items()[selectedIdx]);
    }
    // return false; // implied as long as you don't return true
}

http://jsfiddle.net/vjLqauq5/8/

Roy J
  • 37,999
  • 5
  • 58
  • 88
  • 2
    This works, so +1. I think I'd have to disagree with this UI behaviour though - if I see a scrollable area, I'd expect to be able to scroll it with my wheel... – James Thorpe Aug 10 '15 at 10:55
  • Agree with @JamesThorpe but nice answer mate #roy +1 . cheers – super cool Aug 17 '15 at 07:13
  • As per this link, it looks like mousewheel is deprecated, in favor of "wheel": https://developer.mozilla.org/en-US/docs/Web/API/Element/mousewheel_event#Browser_compatibility – MrBoJangles May 03 '19 at 16:40