Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery mousewheel stop propagation

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;
});
like image 814
clarkk Avatar asked Jun 08 '13 06:06

clarkk


2 Answers

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

like image 177
Chris Spittles Avatar answered Sep 19 '22 00:09

Chris Spittles


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.

like image 31
dkellner Avatar answered Sep 19 '22 00:09

dkellner