Search code examples
javascriptclickconflictmousedown

javascript document onmousedown cancels element onclick


I have document.addEventListener('mousedown', ...) performing some visual feedback to the user. But I also have dynamicaly created elements with elem.addEventListener('click') which are not fired. If I remove document mousedown listener then clicks on elements are triggered (or if I change document's mousedown to click event). Why is that and how to solve this? I would realy need document to handle mousedown and still be able for elements to recieve their click/tap events.

FIDDLE: http://codepen.io/hpet/pen/izpJK if you uncomment document mousedown event, element receives click ok, otherwise click on element is never triggered.

Fiddle updated. Uncomment lines 22/23 (setting position) will not fire click event.


Solution

  • The root cause of your problem is overlapping elements.

    Since you're moving the circle element on top of the square element in your mousedown handler, the subsequent mouseup event will be triggered on the circle. Since that event was not triggered on the square element, no click event will be generated.

    If you have to keep the circle element on top of the square, you can use the pointer-events CSS rule to force mouse events to "go through" the circle element.