I'm trying to create an action where a div is created and immediately "floats" upwards until it's off-screen.
To accomplish this I'm attempting to use a CSS transition, which will be completely driven by JavaScript (due to limitations in my use-case).
A problem occurs when I create an element, assign it it's transition style properties, and then immediately try to kick-off the transition by making a style change (top
).
It looks like a timing issue is happening where the top
style change is firing before the transition becomes available and thus simply moving my div off-screen immediately, rather than actually performing the transition.
Here's a simplified example:
var
defaultHeight = 50,
iCount = 0,
aColors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'];
function createBlock() {
var testdiv = document.createElement('div');
testdiv.className = 'testdiv';
document.body.appendChild(testdiv);
testdiv.style.left = '50%';
testdiv.style.backgroundColor = aColors[iCount % aColors.length];
testdiv.style.width = defaultHeight + 'px';
testdiv.style.height = defaultHeight + 'px';
testdiv.style.fontSize = '30px';
testdiv.style.textAlign = 'center';
testdiv.innerHTML = iCount;
testdiv.style.top = '500px';
testdiv.style.position = 'absolute';
iCount++;
return testdiv;
}
document.getElementById('go').onclick = function() {
var testdiv = createBlock();
testdiv.style.transition = "top 2.0s linear 0s";
setTimeout(function() {
testdiv.style.top = (defaultHeight*-2) + 'px';
}, 0); // <- change this to a higher value to see the transition always occur
};
When the "go" button (see JSBin) is clicked rapidly the div only appears sporadically (presumably due to the timing issue described above).
If you increase the setTimeout
's delay value you can see the transition almost always work.
Is there a way to deterministically kick off a transition immediately after creating an element (without having to resort to a delay)?