I'm writing a JS game which moves IMG elements about by setting their x/y/width/height/opacity and allowing the CSS transition to gradually move it to its target and triggers an event when it arrives. This all works well.
The part I'm having trouble with is creating a new IMG and immediately have it start moving to its target with a transition. I've experimented and the best I can get is for the image to be created already at its target location, I suspect because the target styles have replaced the source styles before the IMG has been added to the document.
How can I create an IMG with:
- Starting x/y/width/height/opacity/etc.
- Target x/y/width/height/opacity/etc.
- Transition time.
- Function to run when it completes the transition.
I hope there's an answer using only plain JS without frameworks such as JQuery, as the objective of this game-writing exercise is to practice JS development.
UPDATE: As requested, one of my failed attempts. I have tried shuffling these comment-separated blocks in various ways but none have produced the desired result of triggering a transition.
function ThrowBall() {
/* Create and configure an image. */
var img = document.createElement("img");
img.src = "https://www.thesunsetlounge.co.uk/Images/DiscoSpot.png"
/* Set starting style. */
img.style.position = "fixed";
img.style.display = "block";
img.style.zIndex = "999";
img.style.top = "100px";
img.style.left = "100px";
/* Add to document. */
document.body.appendChild(img);
/* Set transition. */
img.style.transition = "all 10s";
/* Move to target. */
img.style.left = "300px";
}
/* Run. */
window.onload = ThrowBall;
UPDATE #2:
Thanks to a comment from @Salketer, I was able to resolve my issue by moving the code that sets the CSS and transition-end event into a function and passing that function into window.requestAnimationFrame
.