IvanInTheHat IvanInTheHat - 1 month ago 9
HTML Question

Unexpected ionicons behaviour

Consider this code.
I cannot figure out why it behaves as it does. All I need is the play icon alternating with pause icon everytime I click anywhere inside the

<td>
. It behaves as expected when I click inside the
<td>
but outside the icon itself. However, if I click on the icon itself, it behaves fine the first time, and then stops.

'The ionicon is wrapped in the
<a>
tag, which is a child of the
<td>
element. The event listener is on the
<td>
, so what could be the problem?

Thanks.

Answer

Ok, figured it out. It seems like an artefact that arises from creating an element from a template and the way mouseenter is implemented.

The problem is that the mouseenter event (hoverOn part of the .hover()) triggers when it shouldn't. Each time a new ionicon is created from a template it will trigger the mouseenter event if the cursor moves a little.

Logically mouseenter shouldn't be triggered when the element appears, because mouseenter should trigger when a listener element or its descendent is hovered over, and then only call when the cursor leaves all of the elements associated with the event and then enters again. I think this is an artefact of creating an element from a template like that. Maybe it's because DOM get updated and it discards the fact that the cursor is already within the element. So mouseenter triggers again and in turn triggers creating a new play icon. Then it repeats..

This codepen should explain it well. If you hover over the play button the mouseenter counter will increment each time you move your mouse even a little, because each time a mouse is moved, a new play button is created. If you delete the line that creates a new play button, it behaves as mouseenter should, triggering only when the cursor enters the element.