I am currently working on a JavaScript game that involves moving IMG elements by adjusting their x/y/width/height/opacity properties and utilizing CSS transitions to smoothly move them to their target locations, triggering an event upon arrival. Everything is functioning as expected.
However, I am facing a challenge when it comes to dynamically creating a new IMG element and immediately initiating its movement towards a target with a transition effect. Despite my attempts, the newly created image seems to appear at its target location right from the start, possibly due to the target styles overriding the source styles before the IMG element is fully added to the document.
Can anyone provide guidance on how to create an IMG element with the following features:
- Initial x/y/width/height/opacity settings
- Target x/y/width/height/opacity specifications
- Transition duration
- Function to execute upon completing the transition
I would prefer solutions using plain JavaScript without relying on frameworks like jQuery, as the purpose of this exercise is to enhance my JavaScript development skills through practice.
UPDATE: Per request, here is one of my unsuccessful attempts. I have experimented with rearranging these comment-separated blocks in different ways, but none have achieved the desired outcome of initiating a transition.
function ThrowBall() {
/* Create an image and configure it. */
var img = document.createElement("img");
img.src = "https://www.thesunsetlounge.co.uk/Images/DiscoSpot.png"
/* Set initial styling. */
img.style.position = "fixed";
img.style.display = "block";
img.style.zIndex = "999";
img.style.top = "100px";
img.style.left = "100px";
/* Add it to the document. */
document.body.appendChild(img);
/* Apply transition setting. */
img.style.transition = "all 10s";
/* Move it to the target position. */
img.style.left = "300px";
}
/* Run the function. */
window.onload = ThrowBall;
UPDATE #2:
Thanks to valuable input from @Salketer, I managed to overcome my issue by encapsulating the code responsible for setting CSS properties and defining the transition-end event within a function and passing that function into window.requestAnimationFrame
.