Is there a way for JavaScript to generate an image and smoothly transition it from its initial state to its final style?

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.

Answer №1

The issue you're encountering stems from the fact that the image is immediately set to a left position of 300px, without ever being displayed at 100px. This lack of initial positioning means there's no transition effect required... It's essential to first have the image appear at its initial position before moving it.

function LaunchBall() {

    /* Create and customize an image. */
    var img = document.createElement("img");
    img.src = "https://www.thesunsetlounge.co.uk/Images/DiscoSpot.png"

    /* Set initial styles. */
    img.style.position = "fixed";
    img.style.display = "block";
    img.style.zIndex = "999";
    img.style.top = "100px";
    img.style.left = "100px";

    /* Append to document. */
    document.body.appendChild(img);

    /* Apply transition effect. */
    img.style.transition = "all 10s";

    /* Move to final position. */
    window.requestAnimationFrame(()=>{img.style.left = "300px";});
}

/* Execute. */
window.onload = LaunchBall;

To resolve this, introduce a delay between the two style declarations. I've used requestAnimationFrame due to its effectiveness in DOM manipulation, but any method that runs after the initial rendering of the image would suffice. For instance, employing setTimeout(...,1000); would work too, albeit resulting in a momentary static display of the image!

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

Executing a function from index.html that continuously loops without any limits

I'm currently working on creating a function that displays specific HTML content only to users with certain roles. Here are the functions I've set up for this: nodejs/server.js app.get('/api/isadmin', ensureAuthenticated, function (re ...

Place a button at the center of a table

I am having trouble centering a button that I built inside a table. The CSS doesn't seem to be correct and I can't figure out why. I would appreciate any help with this issue. Additionally, the button needs to be displayed in an email, in case th ...

Can you guide me on implementing first-person controls in react-three-fiber?

I'm attempting to set up a scenario where the camera remains stationary while allowing users to rotate the view around either the y or x axis by dragging their mouse. I'm looking for something akin to the functionality seen on threejs.org/example ...

Preventing Redundancy in Angular 2: Tips for Avoiding Duplicate Methods

Is there a way I can streamline my if/else statement to avoid code repetition in my header component? Take a look at the example below: export class HeaderMainComponent { logoAlt = 'We Craft beautiful websites'; // Logo alt and title texts @Vie ...

Attempting to include a navigation bar within the footer section of my layout page - the master page on my website

Is there a way to add a navigation bar in my footer on the layout page without having to add it to every individual page? I want the icon color for the active page to be red, but only apply this to the current page and not all pages. Currently, when I nav ...

Issue with sticky navbar in parallax design

I have been working on a website where all pages feature a header and a navbar located just below it. As the user scrolls down the page, I want the navbar to stick to the top of the screen once it reaches that position. However, on one specific page, I am ...

Guide on how to align the bootstrap popover's arrow tip with a text field using CSS and jQuery

I have tried multiple solutions from various questions on Stack Overflow, but I am still struggling to position the arrow tip of the bootstrap popover correctly. html: <input type = "text" id="account_create"/> js: $('.popov ...

Unable to activate check box button by clicking on it

Hi there! I am having trouble with a checkbox button on my website. The button appears fine, but for some reason it's not working properly (it doesn't get unchecked when clicked). Can anyone help me fix this issue? I'm still learning HTML an ...

Unable to scroll to top using div scrollTop() function

Here's the fiddle I mentioned: http://jsfiddle.net/TLkmK/ <div class="test" style="height:100px;width:70px;overflow:auto"> Some text here that needs scrolling. </div> alert($('.test').scrollTop()); Feel free to scroll down ...

When working with Angular1+ ES6 and using controller as a class, the utilization of Dependency Injections may be ambiguous within controller functions

I recently started using ES6 class for defining my controller, and here is the syntax I am using: export class SearchBarController { constructor($log) { 'ngInject'; $log.debug("Hello"); } textTyped($log){ $ ...

Adjust the Pivot Point of a GLTF Model in ThreeJS Manually

Hey there, I have a GLTF model that I successfully loaded into my ThreeJS scene by using the code snippet below: gltfLoader.load('assets/models/coin/scene.gltf', (gltf) => { const root = gltf.scene; gltf.scene.traverse(functio ...

Complete guide on modifying CSS with Selenium (Includes downloadable Source Code)

I am looking to switch the css styling of a website using Python and Selenium. My initial step was to retrieve the current CSS value. Now, I aim to alter this css value. The Python code output is as follows: 0px 0px 0px 270px How can I change it from 0 ...

Are web components capable of managing changes in CSS (maybe through cssChangedCallback)?

Is there a way to control the application of CSS to a web component similar to using attributes through attributeChangedCallback. I am currently developing a couple of web components that could benefit from being styled with CSS classes. However, I requir ...

Imitate a hover effect followed by a click to activate the pre-established onclick function

When using Gmail, selecting a message will prompt a bar to appear at the top of the messages table. This bar allows for mass actions to be performed on the selected messages (refer to the GIF photo attached). https://i.stack.imgur.com/XxVfz.gif I have be ...

What is the process for obtaining all of the options from a jQuery datepicker in order to create a new datepicker with identical settings?

Is there a way to easily replicate all options of a jQuery datepicker when creating a new instance? I am trying to duplicate a table that includes 2 datepickers with different settings. For reference, you can view an example here: http://jsfiddle.net/qwZ5 ...

Endless loop in XMLHttpRequest()

I am trying to use Ajax in the code snippet below to continuously retrieve a PHP query result until it reaches "6". The code seems to be functioning correctly, but once the result is "6", the script does not stop running. Instead, my CPU fan starts making ...

Required attributes not found for data type in TypeScript

When the following code snippet is executed: @Mutation remove_bought_products(productsToBeRemoved: Array<I.Product>) { const tmpProductsInVendingMachine: Array<I.Product> = Object.values(this.productsInVendingMachine); const reducedPro ...

In need of assistance with adding a divider within a box using HTML/CSS

As a beginner, I may have messy code but I'm working on creating a job search page with a bar displaying the results like this: I've almost got it, except I can't figure out how to add that divider between PREV, 1 to 100, and NEXT. My curre ...

Creating various visualizations using React

I am new to React, Highcharts, and UI development in general. My goal is to render multiple charts from an array of data. However, I'm currently facing an issue where only the last chart - based on the last data in the array - is displayed on the page ...

Tips for including a variable in formData and the steps for implementing it in an ajax procedure

<input type='file' name='inpfile' id='inpfile' accept='image/*' hidden> javascript code var clicked; $('#btnplusa').click(function(){ clicked = 'a'; $('#inpfile').click ...