简体   繁体   中英

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.

As @Vijai said your problem with the hover event .. And While I don't know a lot about your project and you really need .empty() on hover or you just need to hide() the icon .. You can try this part of code instead of yours

var hovOn = function(event) {
  if($(this).find('a').length < 1){
    $(this).html(playButtonTemplate);
  }else{
    $(this).find('a').show();
  }   
};
var hovOff = function(event) {
  $(this).find('a').hide();
}

Codepen Here

When you click on the <a> tag it seems it is also triggering the parent <td> hover event. Once solution is try the below code for hover.

var hovOn = function(event) {
      if(playOrPause==='play') {

    $(this).html(pauseButtonTemplate);
    playOrPause = 'pause';
  } else {
    $(this).html(playButtonTemplate);
    playOrPause = 'play';
  }
};

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM