Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping propagation of mousedown/mouseup from a click handler

Here's a DEMO.

I have two divs, an inner and an outer:

<div id="outer">
    <div id="inner"></div>
</div>

With some CSS so you can see which is which:

#outer {
    width: 250px;
    height: 250px;
    padding: 50px;
    background: yellow;
}

#inner {
    width: 250px;
    height: 250px;
    background: blue;
}

I try to stop propagation of mousedown and mouseup events from within a click handler like so:

$('#inner').on('click', function(e) {
    e.stopPropagation();
    $(this).css({'background': 'green'});
    return false;
});

$('#outer').on('mousedown', function(e) {
    $(this).css({'background': 'green'});
});

$('#outer').on('mouseup', function(e) {
    $(this).css({'background': 'yellow'});
});

This doesn't seem possible. What does work is calling .stopPropagation from within other mousedown and mouseup calls, as shown here (another DEMO):

$('#inner').on('mousedown', function(e) {
    e.stopPropagation();
    return false;
});

$('#inner').on('mouseup', function(e) {
    e.stopPropagation();
    return false;
});

I may have already answered my own question, but I'm not sure if my approach is the best or most reasonable. Is this the right way to stop an event bubbling up to a mousedown and mouseup?

like image 848
Josh Smith Avatar asked Jan 16 '12 01:01

Josh Smith


People also ask

How do I stop click event propagation?

To stop the click event from propagating to the <div> element, you have to call the stopPropagation() method in the event handler of the button: btn. addEventListener('click', (e) => { e. stopPropagation(); alert('The button was clicked!

Does MouseUp fire before click?

Mouseup is always firing before click, despite this order.

Is Mousedown the same as click?

Note: This differs from the click event in that click is fired after a full click action occurs; that is, the mouse button is pressed and released while the pointer remains inside the same element. mousedown is fired the moment the button is initially pressed.

What is the difference between MouseUp and Mousedown?

MouseDown occurs when the user presses the mouse button; MouseUp occurs when the user releases the mouse button.


1 Answers

Yes. Since mouseclick and mousedown/mouseup are different events, you can't get at one from the other at all - you have to do it from within your own mousedown/mouseup handlers. What you can do is refactor that into a generic method to use in both places:

stopPropagation('#inner', 'mousedown');
stopPropagation('#inner', 'mouseup');

function stopPropagation(id, event) {
    $(id).on(event, function(e) {
        e.stopPropagation();
        return false;
    });
}
like image 176
Jeff Avatar answered Oct 16 '22 11:10

Jeff