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
, andmouseup
are distinct events. Although you might think of aclick
as being amousedown
followed by amouseup
, in reality you might haveclick
events triggered by user actions that don't even involve the mouse, as well as combinations ofmousedown
andmouseup
that don't result in anyclick
events at all.Solution 2:
You could create a simple wrapper-"class", that keeps track of mouse-down and up events:
(function () { varDragDropHandler = { 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-functionalityif(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"