da********@gmai l.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(eleme nt){
// do other stuff
this.eventMouse UpAfterMove =
this.upAfterMov eHandler.bindAs EventListener(t his);
this.eventMouse Move = this.moveHandle r.bindAsEventLi stener(this);
this.eventMouse Up = this.upHandler. bindAsEventList ener(this);
this.eventMouse Down = this.downHandle r.bindAsEventLi stener(this);
this.eventKeyPr ess = this.keyHandler .bindAsEventLis tener(this);
Event.observe(t his.handle, "mousedown" , this.eventMouse Down);
}
Draggable.proto type.downHandle r = function(event) {
// do stuff
Event.observe(d ocument, "mousemove" , this.eventMouse Move);
Event.observe(d ocument, "mouseup", this.eventMouse Up);
Event.observe(d ocument, "keypress", this.eventKeyPr ess);
Event.stop(even t);
};
Draggable.proto type.moveHandle r = function(event) {
// do stuff
Event.stopObser ving(document, "mouseup", this.eventMouse Up);
Event.observe(d ocument, "mouseup", this.eventMouse UpAfterMove);
Draggable.updat eDrag(event);
Event.stop(even t);
};
Draggable.proto type._afterMove Helper = function(){
// do stuff
Event.stopObser ving(document, "mousemove" , this.eventMouse Move);
Event.stopObser ving(document, "mouseup", this.eventMouse UpAfterMove);
Event.stopObser ving(document, "keypress", this.eventKeyPr ess);
};
Draggable.proto type.upAfterMov eHandler = function(event) {
// stuff
this._afterMove Helper();
Event.stop(even t);
};
Draggable.proto type.keyHandler = function(event) {
// stuff
this._afterMove Helper();
Event.stop(even t);
};
Draggable.proto type.upHandler = function(event) {
Event.stopObser ving(document, "mousemove" , this.eventMouse Move);
Event.stopObser ving(document, "mouseup", this.eventMouse Up);
Event.stopObser ving(document, "keypress", this.eventKeyPr ess);
Event.stop(even t);
};