I added a transtionend
callback event to an element. This element has a child that has a transition as well.
The problem is that, when the child's transition ends, its' parent transitionend
event gets called.
I tried adding e.stopPropagation()
to the transitionend
event, but it didn't help. It didn't seem like it did anything. How can I prevent the transitionend
event happening when the child finishes its transition?
var outer = document.getElementById('outer'),
content = document.getElementById('content'),
outerButton = document.getElementById('outerButton'),
contentButton = document.getElementById('contentButton');
outerButton.addEventListener('click', function() {
outer.style.width = (outer.style.width === '300px') ? '500px' : '300px';
});
contentButton.addEventListener('click', function() {
content.style.width = (content.style.width === '150px') ? '250px' : '150px';
});
if ('transition' in document.documentElement.style) {
outer.addEventListener('transitionend', function(e) {
alert('transitionend');
console.log('before');
e.stopPropagation();
console.log('after');
});
}
#outer {
width: 500px;
background-color: orange;
transition: width 0.7s ease-in-out;
}
#content {
background-image: url("http://i.imgur.com/nri7bYd.jpg");
height: 200px;
width: 250px;
transition: width 0.7s ease-in-out;
}
<div id="outer">
<div id="content">This is some content</div>
</div>
<button id="outerButton">Change Width of Outer (orange) Element</button>
<br />
<br />
<button id="contentButton">Change Width of Content (image) Element</button>
What I have understood from the question and comments is that you don't want transitionend event to happen on child element.
From the code above , since you have applied transition end event to your parent (in this case outer), hence this will capture all the child event as well.
Best way to deal with this problem is to add a check, in the method.
if ('transition' in document.documentElement.style) {
outer.addEventListener('transitionend', function(e) {
if(e.target == content) { return;}
console.log('before');
e.stopPropagation();
console.log('after');
});
}
Here e.stopPropagation(); stops the event to further propagate, for example if you had grandParent div , then the event will not go there, but in this case since the event is coming from child, it is catched by outer.addEventListener...So best way is to check the event target and then take a decision.
Hope it helps!!