I'd like to understand why the following code exponentially duplicates transitionend's return.
It doesn't make any sense to me, because they are supposed to have the same behavior and should be executed just once.
The expected behavior is commented below.
(function() {
var animations = {
start: function() {
console.log('animations has started');
this.transition.run();
},
transition: {
duration: 500,
run: function() {
console.log('transitions is running');
const el = document.querySelector('.box');
el.classList.toggle('fadein');
// dont duplicate as expected !!!GOOD BEHAVIOR!!!
/*el.ontransitionend = function(){
console.log('transitionend triggered!');
};*/
// duplicates at every click !!!BAD BEHAVIOR!!!
el.addEventListener('transitionend', function() {
console.log('transitionend triggered');
}, false);
}
}
};
const bt = document.querySelector('button');
bt.addEventListener('click', () => {
animations.start();
})
})();
.box {
width: 100%;
height: 100vh;
background: green;
opacity: 0;
transition: opacity .5s linear;
}
.box.fadein {
opacity: 1;
}
<button>Start Transition</button>
<div class="box"></div>```
It's such weird behavior!
From the MDN event handler docs:
What does this mean?
With
el.ontransitionendyou replace always the "old" event handler, because there can be only one property handler.But with
el.addEventListeneryou always add a new handler, the old one will stay untouched as long as you don`t explicitly remove it.