da********@gmail.com wrote:
In a web page I have a div tag that has a onlick event registered
through the event listener. However, that same div tag also has a
onmousedown - start a drag and drop script
The problem I am having is that once the drag and drop is complete, the
mouse button is released and the onclick event is firing.
Dave,
I have done something very simlar to this. I found that using a click
observer is not good in this situation. Better to watch for mouseup and
mousedown events.
The basics of of the approach I took was to and and remove event
listeners based on what already has occured. Something like
1) initialize the div's related JavaScript object by registering a
mousedown observer
2) in the mousedown handler add mousemove and mouseup observers
3) in the mousemove handler remove the mouseup observer. Now once a
mouse move begins you are no longer also observing for a mouse up.
Here is some code I used based on Prototype.js library for event
handling. People here will certainly caution against the use of this
library. I think this code is quite readable to show you what I did.
What I don't like about it is the unfortunate spagetti code feel of
registering and deregistering all the observers.
function Draggable(element){
// do other stuff
this.eventMouseUpAfterMove =
this.upAfterMoveHandler.bindAsEventListener(this);
this.eventMouseMove = this.moveHandler.bindAsEventListener(this);
this.eventMouseUp = this.upHandler.bindAsEventListener(this);
this.eventMouseDown = this.downHandler.bindAsEventListener(this);
this.eventKeyPress = this.keyHandler.bindAsEventListener(this);
Event.observe(this.handle, "mousedown", this.eventMouseDown);
}
Draggable.prototype.downHandler = function(event){
// do stuff
Event.observe(document, "mousemove", this.eventMouseMove);
Event.observe(document, "mouseup", this.eventMouseUp);
Event.observe(document, "keypress", this.eventKeyPress);
Event.stop(event);
};
Draggable.prototype.moveHandler = function(event){
// do stuff
Event.stopObserving(document, "mouseup", this.eventMouseUp);
Event.observe(document, "mouseup", this.eventMouseUpAfterMove);
Draggable.updateDrag(event);
Event.stop(event);
};
Draggable.prototype._afterMoveHelper = function(){
// do stuff
Event.stopObserving(document, "mousemove", this.eventMouseMove);
Event.stopObserving(document, "mouseup", this.eventMouseUpAfterMove);
Event.stopObserving(document, "keypress", this.eventKeyPress);
};
Draggable.prototype.upAfterMoveHandler = function(event){
// stuff
this._afterMoveHelper();
Event.stop(event);
};
Draggable.prototype.keyHandler = function(event){
// stuff
this._afterMoveHelper();
Event.stop(event);
};
Draggable.prototype.upHandler = function(event){
Event.stopObserving(document, "mousemove", this.eventMouseMove);
Event.stopObserving(document, "mouseup", this.eventMouseUp);
Event.stopObserving(document, "keypress", this.eventKeyPress);
Event.stop(event);
};