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

Reacting to the dynamic removal of spaces

Is there a way to dynamically remove the space between removed chips and older chips in Material-UI when deleting one of them? <div className="row contactsContainer"> {contacts.map((contac ...

Adjust the appearance of an element based on user selection from a dropdown menu under certain circumstances

I am working on creating a dropdown menu using a JavaScript array. My goal is to display a specific span element when certain options are selected. For instance, I want the span to be shown only when options "a" and "c" are selected, but not when option " ...

Is it possible for jQuery datepicker to choose a date over a decade in the past?

Recently, I encountered an issue with jQuery-UI's datepicker where it was restricting me to select birthdays only within the last 10 years. This basically meant that users older than 10 years couldn't be accommodated :) I attempted to override t ...

Activate the button with a tap of the space bar on a webpage

Is it possible to have a button on a webpage triggered both by clicking with the mouse and hitting the spacebar? HTML <div class="col-12 button small-button"> <a onclick="generator()"> <img src="icones%20web%20projeto.p ...

To keep the PHP echo statement inline with the HTML code, simply use the following syntax

(<?php _e( 'Up to', 'test' ); ?> &pound;<?php $current_price = get_field( 'price_details_price_b', 'option' ); $exchange_rate = get_field( 'price_details_exchange_rate', 'option' ); ...

"Troubleshooting: Issue with CSS code on Codepen when trying to create

I am attempting to replicate the Google logo using HTML and CSS. While the code functions properly in browsers, there seems to be an issue with Codepen not positioning the horizontal blue line correctly. How can this be resolved? What adjustments should ...

JavaScript - Separate Artist and Title

In the code snippet below, I am using a Parser script to extract metadata from a live streaming radio station: const Parser = require('../src'); const radioStation = new Parser('http://stream.com/live_32.aac'); radioStation.on(' ...

The inability to display a Stylesheet is due to the unsupported MIME type, even though the MIME type seems to be missing when checking for errors

Every time I try to apply a specific style to a particular page on a website (even though the same style functions properly on other parts of the web server), an error message pops up. The error notification states Refused to apply style from 'styl ...

How can I utilize the context menu feature within a Material React Table row?

I am looking to implement a context menu for each row of the MUI Table, but I haven't found a suitable example. Is there native support for row-level context menus in the MUI Table, or is it possible to add this functionality per row? For reference, ...

I plan to compile a collection of names in a text field and then have the ability to select and access each name individually with just a click

I am currently working on a project that involves creating an admin site using Firebase. One of the main features of the site is large text fields that display information which can be modified. For instance, the user management page includes text fields ...

Show the Select component in a grid format with a list view, displaying three items per row

Within my react Dropdown component, there is currently a list view displayed when an item is selected. However, I am looking to modify it so that the items are arranged in a grid format with 3 items per row. Sample Code: import { Dropdown } from 'pri ...

Can someone clarify the meaning of (e) in Javascript/jQuery code?

Recently, I've been delving into the world of JavaScript and jQuery to master the art of creating functions. I've noticed that many functions include an (e) in brackets. Allow me to demonstrate with an example: $(this).click(function(e) { // ...

When attempting to open a link in a new tab, the ng-click function fails to execute

In Angular, utilizing both the <code>ng-click and ng-href directives at the same time will result in the click function being executed first. In this scenario, clicking on a link that navigates to Google will be prevented and instead an alert will be ...

My CSS files are not being included by grunt-bower-install

As someone who is relatively new to bower and grunt, I'm struggling with some basic tasks. After running bower install --save bootstrap, my goal is to use grunt-bower-install to update my js & css files as per the instructions on their documentat ...

`@keyup.enter event listener will only be triggered upon pressing the Enter key if the focus is on

My login button only seems to work when I press the tab button after entering my email and password. I would like it to work whenever I press the enter key while on the Login page of this VueJS application. This is the HTML template: <template> ...

Steps to programmatically update Node modules:

I am looking to incorporate the use of npm update within a script. Take a look at my code snippet below: var npm = require('npm'); npm.load(function () { npm.commands.outdated({json: true}, function (err, data) { //console.log(data); npm ...

Choose all checkboxes across the entire webpage

Given the code below: <input type="checkbox" name="categories[9507]"> Is there a way to write a JavaScript command that can automatically select all checkboxes with similar naming structures on the entire page? The only difference in the names is t ...

Error encountered while using Jquery's .each() method on a DOM element and attempting to

Trying to utilize the each() function on my DOM to dynamically retrieve a field, I encountered an issue with the following code: var new_entry = new Object(); $('div[name="declaration-line-entry"]').each(function () { new_entry.name = $(this ...

Unable to showcase Mysql search outcomes in a distinct div section

I have been working on a project to showcase MySQL results by utilizing three different sections/divisions. In Division 1, there are radio buttons that allow for selecting and viewing the results based on different criteria. Division 2 contains text indica ...

Ensuring the sort icon is constantly displayed in MudDataGrid

Is there a way to keep the sort icon visible at all times in mudgrid without any default sorting using mudblazor? I have implemented the advanced data grid from the following link:- I have attempted using sortable=true on both the column and datagrid but ...