Home > Back-end >  onclick handler doesn’t always run while child elements are being updated
onclick handler doesn’t always run while child elements are being updated

Time:09-16

I have a row of <a> elements which have onclick handlers:

<a onclick="selectCoin('MER');">
<div id="MER">
...
</div>
</a>

The interior of the <div> child gets overwritten continuously to update some text inside the buttons. The updating is done by querying the #MER selector, and assigning to innerHTML. I noticed that the onclick handlers don’t always run if the <div> element is being updated in the background. Oftentimes, I have to click it two or three times before the onclick hander actually gets invoked. If I make the <div> elements static, the onclick handlers run consistently and reliably.

Why does updating the <div> child cause the onclick handler to stop working consistently? How do I fix this issue, while still updating the contents of the button?

CodePudding user response:

To generate a click event, an element must receive a mousedown followed by a mouseup.

If the element goes away after the mousedown and is replaced with a new one, the click event is not sent.

You could do your own mousedown/mouseup detection on the <a> element, but if nothing inside the element is really clickable, you can disable mouse events on the child elements, so that they all occur on the <a> element

on your "MER" div:

style="pointer-events:none;"

Working fiddle:

https://jsfiddle.net/8h17rcpz/

CodePudding user response:

click events are only generated if a mousedown and mouseup pair of events are fired consecutively on the same element, which is not going to happen if it gets swapped between down and up events.

The simplest solution would be to replace onclick in HTML source with onmouseup. What side effects or undesirable behavior that might produce is not possible to assess from the information provided.

  • Related