Why is my animation "replayed" when an element is added via innerHTML?
Asked Answered
L

1

7

I have a little script that adds a div named "doge" using innerHTML when clicking on a button on my page, and on this page there's a div with a CSS keyframes animation.

However, when I click on the button to add the div named "doge" on my page, the CSS animation is "replayed". Why? How can I fix that?

function addHtml() {
    document.getElementById("wow").innerHTML += '<div class="doge">such wow</div>';
}
@keyframes color {
    10% {
        background: #4CAF50;
    }
    50% {
        background: #3F51B5;
    }
    100% {
        background: #009688;
    }
}

.myDiv {
    background: #000;
    color: #fff;
    animation: color 1s;
}

.doge {
    background: #F57F17;
}
<div id="wow">
    <div class="myDiv">Hi!</div>
    <br>
    <button onclick="addHtml()">Add HTML!</button>
</div>

JSFiddle

Lychnis answered 21/12, 2015 at 17:26 Comment(0)
S
6

It's because you're modifying all of the element's HTML when you modify the .innerHTML property.

According to MDN:

.innerHTML - Removes all of element's children, parses the content string and assigns the resulting nodes as children of the element.

In doing so, the DOM assumes that the .myDiv element has just been added which means that the animation is going to be replayed. To work around that, use the .appendChild() method instead:

Updated Example

var div = document.createElement('div');
div.textContent = 'such wow';
div.className += 'doge';
document.getElementById("wow").appendChild(div);

Alternatively, as Teemu points out, you can also use the .insertAdjacentHTML() method:

Updated Example

document.getElementById("wow").insertAdjacentHTML('afterend', '<div class="doge">such wow</div>');
Stromberg answered 21/12, 2015 at 17:29 Comment(3)
@MrZrn See the link in my answer.Stromberg
working, but there's no solution to directly add my html code ? like innerHtml ?Lychnis
@MrZrn Actually there is, but I'd still prefer Josh's code as a primary method to add content to a page.Abbe

© 2022 - 2024 — McMap. All rights reserved.