migreva
migreva

Reputation: 876

Velocity JS and Dynamically Added DOM Elements

I have two CodePens that describe my problem. I'm using Velocity to animate React-rendered elements on a page.

The objective is to move these "articles" up and down the page based on rank. They are absolutely positioned, and I determine the position on the page based on rank * height.

The working example successfully displays all the elements, then after a setTimeout of 2 seconds it reverses the order.

The non-working example is supposed to do the exact same thing, but the only one it moves around the page is the final DOM object (id=article-5).

The only difference between the examples is that the working example has already-rendered DOM elements on the page, while the non-working example renders the HTML via JavaScript

var articlesContainer = document.getElementsByClassName('articles')[0];
for (var i = 1; i <= 5; i++) {
  articlesContainer.innerHTML = articlesContainer.innerHTML + '<div id=article-' + i + '></div>';
}

Not really sure why that dynamic adding of the HTML elements would break this. It's worth noting that the first 4 elements that fail to animate have the class velocity-animating, which means that Velocity at least tried to animate the object, but seemingly failed along the way somewhere.

Any ideas?

Upvotes: 2

Views: 861

Answers (1)

Alexandre Kirszenberg
Alexandre Kirszenberg

Reputation: 36418

When you do articlesContainer.innerHTML = newHTML, you're unmounting all nodes in articlesContainer and mounting new ones. Velocity/React thus operate on detached nodes, except for the last article node which is the only one not unmounted. Use document.createElement and node.appendChild instead:

var articlesContainer = document.getElementsByClassName('articles')[0];
for (var i = 1; i <= 5; i++) {
  var div = document.createElement('div');
  articlesContainer.appendChild(div);
}

Upvotes: 2

Related Questions