Javascript click and mousedown conflicting
Try this way. event.stopPropagation
does not stop the click event from firing after mousedown. Mousedown and click events are not related to each other.
var mousedownFired = false;
$("#id").on('mousedown', function(event) {
mousedownFired = true;
//code
});
$("#id").on('click', function(event) {
if (mousedownFired) {
mousedownFired = false;
return;
}
//code
});
Update:
Mouse events are triggered like this:
mousedown
click
mouseup
If mousedown is triggered, the mousedownFired
variable will be set to true
. Then in the click event, it will return
(i.e. not continue processing the click event), and the mousedownFired
variable will be reset to false, so future click events will fire normally. Not going to consider two mousedown or two click events.
What you likely want to do is attach the event handlers to the parent container rather than the individual child divs. By doing this, as new children are created, you don't need to add additional event handlers.
For example:
$("#parentDiv").on('click','.childDiv',function() {
event.stopPropagation();
}).on('mousedown','.childDiv',function() {
// your dragging code
});
When you provide a selector to the .on() function, the function passed is called for descendants that match that selector.