What causes my animation to “reset” upon adding a new element using innerHTML?

One of the functionalities on my webpage involves a script that inserts a div called "doge" using innerHTML when a button is clicked. Additionally, there is a CSS keyframes animation applied to another div on the same page.

However, whenever the button is clicked to add the "doge" div, the CSS animation restarts. Why does this happen and how can it be resolved?

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

Answer №1

When you update the .innerHTML property of an element, it modifies all of the element's HTML content.

As stated on MDN:

.innerHTML - This property removes all existing children of the element, parses the new content string, and assigns the resulting nodes as the children of the element.

This action causes the DOM to treat the updated element as if it has just been added, triggering any associated animations to replay. To prevent this, consider using the .appendChild() method instead:

See Updated Example

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

Another approach, as pointed out by Teemu, is to utilize the .insertAdjacentHTML() method:

See Updated Example

document.getElementById("wow").insertAdjacentHTML('afterend', '<div class="doge">such wow</div>');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to connect CSS and JavaScript files to index.html on Heroku while utilizing Node.js

Trying to set up a Tic Tac Toe game in my app.js file, but encountering some issues with linking files in index.html. app.set('port', (process.env.PORT || 5000)) //serve static files in the public directory app.use(express.static('public& ...

CSS - Adjusting width based on height ratio

I'm in the process of developing a website and could use some guidance. I have a specific section where I am aiming for the height to be 79.6% of the body, with the width of that div being dependent on its height. Thus far, my research has only yielde ...

Updating content in AngularJS based on the sidebar can be achieved by following these steps:

Yesterday, I posed a question about how to implement multiple views with Angular in order to have a header and sidebar. After receiving some helpful insights, I was able to make progress on creating a header and sidebar for my AngularJS App. You can view ...

Calculating the vertical distance between an element and the top of the page

I am attempting to calculate the distance between the top of an element and the top of the page every time the user scrolls. Although I have managed to make it work, the issue arises when scrolling - the distance remains unchanged. I tried addressing this ...

Please ensure you have selected at least one item before submitting the form

I have been working on validating a form using a combination of bootstrap and angularjs. The form includes two groups of checkboxes that need to be validated. It is required for the user to select at least one checkbox from each group in order for the Subm ...

What are some ways to slow down the speed of my animation?

Currently, I am creating a HTML5 game where I have implemented javascript to make my character move in response to the user pressing the arrow keys. The movement animation consists of 6 sprites. However, I have encountered an issue where when I hold down ...

Here's a simple script to display a div or popup only once in the browser using plain vanilla JavaScript

// JavaScript Document I'm attempting to make a popup appear in the browser only once. I believe using local storage is the key, but all I can find are solutions involving jQuery. I really want to achieve this using plain JavaScript without relying ...

Modify the button's color based on a separate column within the table

Currently, I am implementing Datatables along with X-editable and including some bootstrap buttons within a table. My objective is to change the color of the button in the 'Validated' column to green when the user updates the editable 'Statu ...

Applying CSS rules from an array to elements by looping through

I'm looking for a way to allow users to input CSS styles and have those styles applied to the last selected element, which is determined by the "rangeselector" variable. Currently, the code selects the correct element, but only the first CSS rule is b ...

The functionality of jQuery smooth scrolling to an anchor is only effective when the page is at the top and there is

Currently, I am working on designing a simple one-page website featuring a fixed menu that smoothly scrolls to specific sections on the page upon clicking the menu items. However, I have encountered an issue where the scrolling works perfectly only when t ...

Pause the jquery script when a key is pressed

Currently, I have a script that loads a php file within a div and automatically refreshes every 5 seconds. Check out the code below: $("#load_timeout").load("time_out.php"); var refreshId = setInterval(function() { $("#load_timeout").load('time_o ...

What is the best way to incorporate polling into the code provided below? I specifically need to retrieve data from the given URL every 60 seconds. How should I go about achieving this

Can you assist me in integrating polling into the code below? <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script src="https://code.highcharts.com/highcharts.js"> ...

Python Selenium Timeout Exception Handling

Looking for a solution: def get_info(url): options = webdriver.ChromeOptions() options.headless = True chrome_browser = webdriver.Chrome('./chromedriver', chrome_options=options) chrome_browser.get(url) name = chrome_browser.f ...

Can you extract information from the XML file and modify the anchor tags?

<description> <div class="field field-name-field-image field-type-image field-label- hidden"><div class="field- items"><div class="field-item even"><a href="/news/news/vg"> ...

Encountering an issue while sending JSON data to a WebAPI that contains an image in bytes format - Receiving an error message stating: "The expression is too long or

My experience with JSON is limited, but I'm currently developing a web service that will receive JSON data from an iOS device and insert it into a database. However, I've encountered an issue with the size of the image byte data which is causing ...

Having trouble making elements in Tailwind CSS take up the entire page? Seems like they're getting stuck in smaller containers instead

I've been working on creating a layout for my webpage that is similar to the one found here: However, despite using Tailwind CSS, I'm having trouble with the flex styling and getting it to display correctly. import { ChevronRightIcon, HomeIc ...

Invoking Node to utilize React/Webpack module code

Trying to figure out how to integrate client-side import/export modules into a Node.js require script within my custom NextJS webpack config: module.exports = { webpack: (config, options) => { if (options.isServer) { require("./some-scr ...

jquery expanding the width of the final element

Is there a way to increase the width of the last 'th' in a string? I want it to be the current width plus 20px. Here is the code on Fiddle var header="<th id='tblHeader_1' style='width: 80px;'><span>Id</span&g ...

Issue with React when attempting to add a secondary class to Toggle component

Is there a way to add a second class to my <div> with the class "button"? When I try to append 'toggle-button', the class doesn't seem to work. <CSSTransitionGroup transitionName="buttonAninmated" transitionEnterTimeout={30 ...

Ways to conceal numerous objects

I need to create a function where I can hide multiple elements by pressing a button based on the value of checkboxes. If a checkbox is checked, the corresponding element should be hidden. Currently, I have some code that only works for the first element: ...