1

I'm using this bit of code to remove an element from the DOM once its CSS transition has completed.

elem.addEventListener('transitionend',function(e) {
    this.parentNode.removeChild(this);
}, false);

But since the transition affects two properties opacity 1 -> 0, height 20px -> 0, the event fires twice, and errors on the second firing (since the element has been removed from the DOM at that point).

I tried testing for the property (as seen here: https://stackoverflow.com/a/18689069/1058739), but then obviously THAT test then fails instead.

Surely when an element is removed from the DOM all event listeners attached to it should also be removed?

What's the trick that I'm missing here?

thanks

Community
  • 1
  • 1
Codemonkey
  • 4,455
  • 5
  • 44
  • 76

1 Answers1

2

Why would detaching an element from the DOM remove all event handlers? The element still exists, just not in the DOM. Imagine trying to move an element from one parent to another

element.parentElement.removeChild(element)
newParent.appendChild(element)

Do you really think detaching all event handlers would be a good idea?

That being said, you can solve your issue in two ways.

Check if the element has a parent

elem.addEventListener('transitionend', function(e) {
    if (this.parentNode) {
        this.parentNode.removeChild(this);
    }
}, false);

or

Detach the event listener

var onTransitionEnded = function (e) {
    this.parentNode.removeChild(this);
    this.removeEventListener('transitionend', onTransitionEnded);
}
elem.addEventListener('transitionend', onTransitionEnded)
Nikola Dimitroff
  • 6,127
  • 2
  • 25
  • 31
  • Good point. My brain doesn't seem to be firing today. I've gone for the second option, thanks. Is there a third way, to "unset" the element entirely? – Codemonkey Jan 07 '16 at 14:52
  • Not really. You can't remove all event listeners without resorting to hacks such as [cloning the element and replacing it](http://stackoverflow.com/questions/9251837/how-to-remove-all-listeners-in-an-element) or [intercepting `addEventListener`](http://stackoverflow.com/a/29930689/1115693) – Nikola Dimitroff Jan 07 '16 at 15:00