Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery event.stopPropagation() not working

In my html I have a span of class dragHandle embedded within a li.

<div class='treeView'>
    <ul class='tree'>
        <li><span class="dragHandle"></span>Item 1
            <ul>
                <li><span class="dragHandle"></span>Item 2 <a href="#">link</a></li>
            </ul>   
        </li>
</ul>

I attach event handlers using jQuery as follows:

$(".tree li").click(function(event) {
    alert("click");
    event.stopPropagation();
});

$(".dragHandle").mousedown(function(event) {
    alert("down");
    event.stopPropagation();

});

$(".dragHandle").mouseup(function(event) {
    alert("Up");
    event.stopPropagation();

});

When I mousedown and mouse up over the element I get the down and up alerts, however I also get the click alert of the li's event handler too. I thought that this should be prevented from by the call to event.stopPropagation in the mousedown and mouseup handlers. How do I stop the click event being called for mousedown/up events on the dragHandle?

TIA, Adam

like image 964
apchester Avatar asked Jul 26 '09 16:07

apchester


1 Answers

How do I stop the click event being called for mousedown/up events on the dragHandle?

You capture... and eat... that event:

$(".dragHandle").click(function(event) { event.stopPropagation(); });

The key here is that click, mousedown, and mouseup are distinct events. Although you might think of a click as being a mousedown followed by a mouseup, in reality you might have click events triggered by user actions that don't even involve the mouse, as well as combinations of mousedown and mouseup that don't result in any click events at all.

like image 143
Shog9 Avatar answered Oct 07 '22 19:10

Shog9