Dynamic JavaScript animation to retrieve the position of an element on-the-fly

I am currently exploring the world of animation in JavaScript and I have a few practical questions. In my script, I am attempting to "launch" a "rocket" upon clicking a "button". What I've observed is that although my function calculates values as intended, the rocket's position on the webpage does not change until the function completes.

Here are my questions:

Is there a way to dynamically update the location (rocket.style.top) of the rocket within my function? If not, what would be a more effective approach to updating the location? Should I consider alternatives to using an event listener on a button?

var button = document.querySelector('.button');
var rocket = document.querySelector('.rocket');
var x = rocket.offsetTop;
var a = 1;

function launch() {
  while (a < 1000) {
    console.log(x);
    console.log(a);
    console.log(rocket.style.top);
    rocket.style.top = x - a + 'px';
    a += a;
    sleep(1000);
  }
}

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds) {
      break;
    }
  }
}

button.addEventListener('click', launch);
div.button {
  font-family: impact;
  letter-spacing: 1px;
  text-transform: uppercase;
  margin: auto;
  text-align: center;
  background-color: rgba(255, 0, 0, 1);
  border-style: solid;
  border-width: 1px;
  border-radius: 100px;
  width: 75px;
  height: 25px;
  padding: 25px 0;
  cursor: pointer;
}

div.rocket {
  position: absolute;
  background-color: rgba(0, 0, 0, .5);
  width: 25px;
  height: 25px;
  bottom: 0%;
  left: 5%;
}
<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <div class='button'>launch</div>
  <div class='rocket'></div>
</body>

</html>

Answer №1

You can achieve this functionality with the help of jQuery:

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

$('.button').click(async function() {
  var a = 0;
  var x = 10;
  while (a < 50) {
    var upd = String(x-a) + 'px';
    $('.rocket').css("margin-bottom", upd);
    a += -x;
    await sleep(50);
  }
});
div.button {
  font-family: impact;
  letter-spacing: 1px;
  text-transform: uppercase;
  margin: auto;
  text-align: center;
  background-color: rgba(255, 0, 0, 1);
  border-style: solid;
  border-width: 1px;
  border-radius: 100px;
  width: 75px;
  height: 25px;
  padding: 25px 0;
  cursor: pointer;
}

div.rocket {
  position: absolute;
  background-color: rgba(0, 0, 0, .5);
  width: 25px;
  height: 25px;
  bottom: 0%;
  left: 5%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <div class='button'>launch</div>
  <div class='rocket'></div>
</body>

</html>

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

Could there be a more efficient method to enable support for all video formats?

I have a case statement in my video validation function that checks for specific file extensions of video formats. However, I am wondering if there is a shorter way to write the code in order to allow all video formats instead of creating a long list of al ...

Conceal a div and label after a delay of 5 seconds with a JavaScript/jQuery function in C#

Here is a sample div: <div class="alert alert-success alert-dismissable" runat="server" visible="false" id="lblmsgid"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> ...

A guide to efficiently reusing parameter definitions in functions using JSDoc

Currently, I have HTTP handlers set up in my express application. I want to use JSDoc annotations to document these handlers in a reusable manner. Here is what I currently have: /** * * @param {functions.Request} req * @param {functions.Response} res ...

Best practices for displaying a Multidimensional JSON Object using JavaScript

Within my current project, I have a JSON object structured as follows: { "face": [ { "attribute": { "age": { "range": 5, "value": 35 }, "gender": { "confidence ...

Problem with ng-include in ng-view templates

Directory Layout: --app --partials --navbar.html --submit --submission.html index.html Using ng-include in submission.html: <ng-include src="'app/partials/navbar.html'" ></ng-include> However, the navbar does not displa ...

Node.JS Logic for Scraping and Extracting Time from Text

Currently, I am working on developing a web scraper to gather information about local events from various sites. One of my challenges is extracting event times as they are inputted in different formats by different sources. I'm seeking advice on how t ...

Unable to receive notifications within an AngularJS service

<!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <body> <div ng-app="canerApp" ng-controller="canerCtrl"> <button ng-click="click()"> ...

Encountering a "Element is not defined" error in Nuxt when trying to render Editor.js and receiving

I've been working on creating an editor using Editor.js within my Nuxt project, but it seems like the editor isn't initializing properly when I render the page. import EditorJS from '@editorjs/editorjs'; interface IEditor { editor: E ...

HTML is being incorrectly rendered by the Express framework

Looking to Use HTML as View Engine in Express? After going through the link, I attempted to start my server with an index.html file on port 8001. However, it failed to render correctly and showed an error in the console: Server Started Error: SyntaxError ...

Enhance your SVG image in D3 by incorporating a drop-shadow effect

Trying to apply a drop-shadow effect to an SVG image using D3. Check out my code below and see the example block here: var imgurl = 'http://www.logo-designer.co/wp-content/uploads/2015/08/2015-Penn-State-University-logo-design-4.png'; var mar ...

Ways to reduce the width of a flex box

I am facing an issue with my main container where I have two items placed on the same line. Item 1 is an image linked to a URL and it should be positioned at the far left of the container. On the other hand, item 2 contains a font awesome icon that needs t ...

What is the best method for storing a modest number of images in a single file using Python?

As a beginner programmer, I am embarking on the journey of creating a basic 2D animation software for a school project. My goal is to enable users to save their animations as a single file that can later be loaded by the program. This will involve storing ...

Guide on deleting an element from an object array based on the content of a specific field (resulting in undefined mapping)

I am working on integrating a task list feature using React. I have created a state to store the id and content of each task: this.state = {tasks: [{id: 123, content: 'Walk with dog'}, {id: 2, content: 'Do groceries'}]} Adding elements ...

performing functions concurrently within angularjs

I am currently utilizing angularjs 1.0 within my application. There is a dropdown on my cshtml page <select tabindex="2" id="Employee" ng-model="models.SelectedEmployee" ng-change="changeEmployee()" disabled="disabled" class="Answer" size="6"> < ...

Instructions for incorporating a personalized document in NextJs version 13

In order to enhance the design of my upcoming Next.js 13 project, I am looking to integrate a custom design system package. This particular package necessitates the creation of custom documents within the page directory, as outlined in the official Next. ...

Unable to fix gap at the base of the jumbotron

Utilizing the jumbo tron to display a hero image of psd, there seems to be a gap at the bottom that I have tried to adjust with margin-bottom: 0px without success. .jumbotron { background-image: url(image/background.png); background-repeat: no- ...

Is there a way to eliminate a specific input box using the jquery remove function?

I've been working on some code and have run into an issue. Currently, the remove function only works on one input box that is created with the append function. I would like it to be able to work on every input box generated through the append function ...

Guide to implement a confirmation box in PHP

I recently set up a Joomla article and integrated the Sourcerer Joomla extension to include JavaScript and PHP in my project. Currently, I am developing a course purchase site where users can buy courses from owners and credits are deducted upon every purc ...

Encountering the error message "The getStaticPaths function in Next.js requires the 'id' parameter to be provided as a string"

Having an issue with the getStaticPaths function. Every time I attempt to create a dynamic display using a parameter, it gives me an error message: A required parameter (id) was not provided as a string in getStaticPaths for / movies / [id]. However, if ...

The SVG image exceeds the boundaries of the parent column div in bootstrap

I am struggling to make a SVG fit inside a column in a bootstrap div with col-lg-4. I tried using img-fluid, but it did not work as expected. The SVG should automatically adjust its size to fit the parent div. However, that is not happening. .star-ratin ...