Nicoll
Nicoll

Reputation: 257

How to delete this element after it runs the animation?

The delelement code is working fine but I want to delete the element after the css animation is finished for "delorean", then I need the animation to start again every time the button is clicked, how can I use my "delelement" code to achieve this? thanks.

function touchDelorean(event) {
    event.preventDefault();
    if (showDelorean == true) {
        delorean();
    }
}

function delorean() {
    var image = document.createElement("img");
    image.id = "delorean";
    image.src = "Images/delorean/" + where + ".png";
    document.getElementById("deloreanContainer").appendChild(image);

//  delelement("deloreanContainer");
}

function delelement(elem) {
    var element = document.getElementById(elem);
    while (element.firstChild) { element.removeChild(element.firstChild); }
}

CSS

#delorean {
position: absolute;
top: 0%;
left: 0%;
width: 29%;
height: 9.8%;
opacity: 1.0;
-webkit-animation: delorean_anim 10s linear;
-webkit-animation-direction: normal, horizontal ;
-webkit-animation-timing-function: cubic-bezier(1, 0, 1, 0);
}

@-webkit-keyframes delorean_anim {
0% { -webkit-transform: translate(-24vw, 0vw) scale(0.6, 0.6) rotate(0deg) }
20% { -webkit-transform: translate(137vw, 36vw) scale(3.5, 3.5) rotate(0deg) }
100% { -webkit-transform: translate(137vw, 36vw) scale(3.5, 3.5) rotate(0deg)}
}

Upvotes: 0

Views: 69

Answers (2)

jnes
jnes

Reputation: 1083

On the element that runs the animation, given that it is image you can add an eventlistener..

// Chrome, Safari and Opera
image.addEventListener('webkitAnimationEnd', function() {
  image.remove()
});

// Standard syntax
image.addEventListener('animationend', function() {
  image.remove()
});

If you're dealing with a css transition and not a css animation then you're looking for transitionend. These events can however be unreliable sometimes so if you know the length of the animation, you're better off with setTimeout as suggested above.

In react.js the infamous CSSTransitionGroup component had many problems due to the transition event not fireing as expected. They "solved" the problem by requiring specifying transition timeout values for the component..

Upvotes: 2

Use setTimeout() and do a time equal or greater to that of your CSS Transition time... so if:

transition: all 3s ease;

then...

function delorean() {
    var image = document.createElement("img");
    image.id = "delorean";
    image.src = "Images/delorean/" + where + ".png";
    document.getElementById("deloreanContainer").appendChild(image);

    setTimeout( function { delelement("deloreanContainer"); }, 3000 );
}

function delelement(elem) {
    var element = document.getElementById(elem);
    while (element.firstChild) { element.removeChild(element.firstChild); }
}

Upvotes: 2

Related Questions