JQuery Event.stopPropagation() Not Working
-
Solution 1:
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, andmouseupare distinct events. Although you might think of aclickas being amousedownfollowed by amouseup, in reality you might haveclickevents triggered by user actions that don't even involve the mouse, as well as combinations ofmousedownandmouseupthat don't result in anyclickevents at all.
Solution 2:
You could create a simple wrapper-"class", that keeps track of mouse-down and up events:
(function () { var DragDropHandler = { isDrag: false, mouseDownHandler: function (event) { alert("down"); event.stopPropagation(); this.isDrag = true; }, mouseUpHandler: function (event) { alert("Up"); event.stopPropagation(); this.isDrag = false; }, clickHandler: function (event) { event.stopPropagation(); // Check if we've already received a mouseDown-event. If we have, // disregard the click event since we want drag-functionality if(this.isDrag) { return; } alert("click"); } }; $(".tree li").click(function(event) { DragDropHandler.clickHandler.call(DragDropHandler, event); }); $(".dragHandle").mousedown(function(event) { DragDropHandler.mouseDownHandler.call(DragDropHandler, event); }); $(".dragHandle").mouseup(function(event) { DragDropHandler.mouseUpHandler.call(DragDropHandler, event); }); })();This creates a closure and delegates the event handling to the DragDropHandler-object. Note that I've used function.call (the first parameter is the context) to ensure that this refers to the DragDropHandler-object inside its methods. Since we have created an anonymous function that can not be reached from global space, I think it's acceptable to use the DragDropHandler reference inside the wrapper event handlers.
Post a Comment for "JQuery Event.stopPropagation() Not Working"