Question

This is driving me nuts. I'm getting multiple mouseout events registering even though I'm getting rid of them with removeEventListener(). I've tried all kinds of variations of this. Essentially, once the mouseout event happens, I want to get rid of it because the user will be rolling over different images to see a large preview. It works fine, but the multiple events registered are ticking me off.

this.removeEventListener('mouseout', handler, false);

and nothing. I'm not sure what I'm doing here. I can't seem to get rid of the mouseout events and they just keep on piling.

document.querySelector('.grid').addEventListener('mouseover',function(e) {
  if (e.target.tagName==='IMG') {
    var myElement=document.createElement('div');
      myElement.className='preview';
      e.target.parentNode.appendChild(myElement);

    var handler = e.target.addEventListener('mouseout', function (d) {
      var myNode = d.target.parentNode.querySelector('div.preview');
      console.log(d.target.parentNode);
      if (myNode) {
        myNode.parentNode.removeChild(myNode);
      }
      this.removeEventListener('mouseout', handler, false);
    });
  } //
}, false); // addEventListener
Was it helpful?

Solution

addEventListener does not return a value, so handler is undefined and the call to removeEventListener will fail.

Use a named function expression instead:

// give the function a name                    vvvvvvv
e.target.addEventListener('mouseout', function handler(d) {
  // ...
  this.removeEventListener('mouseout', handler, false); // use name
}, false); // <- don't forget `false` here, just in case

The name of the function is only accessible inside the function itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top