Reputation: 23
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!
Upvotes: 2
Views: 178
Reputation: 3116
From the MDN event handler docs:
To set event handler code you can just assign it to the appropriate onevent property. Only one event handler can be assigned for every event in an element. If needed the handler can be replaced by assigning another function to the same property.
The most flexible way to set an event handler on an element is to use the EventTarget.addEventListener method. This approach allows multiple listeners to be assigned to an element, and for listeners to be removed if needed (using EventTarget.removeEventListener).
What does this mean?
With el.ontransitionend
you replace always the "old" event handler, because there can be only one property handler.
But with el.addEventListener
you always add a new handler, the old one will stay untouched as long as you don`t explicitly remove it.
Upvotes: 3