jQuery mousewheel stop propagation
Asked Answered
C

2

6

How to stop propagation with the mousewheel event listener?

When using the mousewheel over the content element the whole document is scrolling too.

This doesn't work:

content.on('mousewheel', function(e, delta){
    content.scrollTop(content.scrollTop() - (40 * delta));
    set_bar();
    e.stopPropagation();
});

solution

content.on('mousewheel', function(e, delta){
    content.scrollTop(content.scrollTop() - (40 * delta));
    set_bar();
    return false;
});
Creaturely answered 8/6, 2013 at 6:21 Comment(2)
AWESOME! I set stopPropagation and then returned false. Any drawbacks you know of, by returning false? I had no trouble but I vaguely remember reading dire warnings about this before.Toluol
It might help if you move the solution down to the answer then marked it as resolved. That way it doesn't show up in the unanswered section.Taddeo
B
6

I think you are confusing stopPropgation and preventDefault.

  • stopPropagation stops the event from bubbling up the event chain.

  • preventDefault prevents the default action happening on the element. In this case it will prevent scrolling, for a click event on an anchor for instance it will stop the link taking you to the URL defined in the href attribute.

  • return false on the other hand does both of these things.

Its an important distinction to make as you might want to use event bubbling for event delegation while preventing the default action at the same time.

See these two posts for more information:

Difference between preventDefault and return false

Difference between preventDefault and stopPropagation

Breannabreanne answered 27/2, 2014 at 9:35 Comment(0)
P
3

The original solution is very close.
Here's what worked:

    $(".myScrollableDiv").on("mousewheel",function(e) {
        var scrollRate = 100;
        var $t = $(this);
        var dy = e.originalEvent.deltaY * scrollRate;
        $t.scrollTop($t.scrollTop() + dy);
        e.preventDefault();
    });

I think the main reason is that jQuery doesn't give us a second parameter (delta) but it can be found in the event itself. Otherwise it's fine.

Personable answered 2/1, 2017 at 0:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.