Using requestAnimationFrame to animate several independent objects

I'm currently working on animating two different objects: a square and a circle. Each object has its own button to initiate the animation, which involves moving the object from left to right. However, I've run into an issue where clicking on one button causes the other object to move back to the left position.

I believe there must be an object-oriented solution to this problem, but my searches haven't yielded any understandable results. Any suggestions or guidance would be greatly appreciated!

$(document).ready(function() {
  // JavaScript logic for object animations
});
html {
  /* CSS styles for HTML */
}
body {
  /* CSS styles for body */
}
.container {
  /* Container CSS styles */
}
.square_css {
  /* Square CSS styles */
}
.circle_css {
  /* Circle CSS styles */
}
.shapeText {
  /* Shape text CSS styles */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<html lang="en">

<head>
  <link rel="stylesheet" type="text/css" href="path/to/index_Main.css" />
</head>

<body>

  <div>
    <input type="button" id="moveSquare" value="Move Square" />
  </div>

  <div>
    <input type="button" id="moveCircle" value="Move Circle" />
  </div>

  <div id="square" class="square_css">
    <div id="squareText" class="shapeText"></div>
  </div>

  <div id="circle" class="circle_css">
    <div id="circleText" class="shapeText"></div>
  </div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script type="text/javascript" src="path/to/index_main.js"></script>
</body>

</html>

Answer №1

The issue arises from both animations sharing the same variable starttime.

To resolve this, each animation needs its own unique starttime.

There are various ways to achieve this, one simple approach is to pass a start time to move() along with other parameters from the click handlers. Additionally, since move() calls itself, the starttime must be passed to the next call as well.

$(document).ready(function() {
var square = $('#square').css({
'top': '100px',
'left': '0px',
'color': 'white',
'position': 'fixed',
'text-align': 'center'
});
var circle = $('#circle').css({
'top': '300px',
'left': '0px',
'color': 'white',
'position': 'fixed',
'text-align': 'center'
});

var squareText = $('#squareText');
var circleText = $('#circleText');

var pos_square = square.position();
var pos_circle = circle.position();

squareText.html(pos_square.top + 'px' + '<br/>' + pos_square.left + 'px');
circleText.html(pos_circle.top + 'px' + '<br/>' + pos_circle.left + 'px');

$('#moveSquare').on('click', function() { // button
console.log('movesuqare here');
requestAnimationFrame(function(timestamp) {
move(timestamp, timestamp, square, squareText, 800, 5000);
});
});

$('#moveCircle').on('click', function() { // button
console.log('movecircle here');
requestAnimationFrame(function(timestamp) {
move(timestamp, timestamp, circle, circleText, 800, 1000);
});
});

function move(starttime, timestamp, element, elementText, distance, duration) {
var runtime = timestamp - starttime;
var progress = runtime / duration;
progress = Math.min(progress, 1);
var leftPos = (distance * progress).toFixed(0) + 'px';
element.css({
left: leftPos,
position: 'absolute'
});
element.css({
'text-align': 'center'
});
var topPos = element.css('top') + '<br/>';
elementText.html(topPos + leftPos);
console.log(element.prop('id') + leftPos);
if (runtime < duration) {
requestAnimationFrame(function(timestamp) {
move(starttime, timestamp, element, elementText, distance, duration);
});
}
}
});
html {
  position: fixed;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
}

body {
  font-family: 'Courier New';
  color: black;
  font-size: 15px;
  width: auto;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
}

.container {
  width: 100px;
  height: 100px;
}

.square_css {
  width: 100px;
  height: 100px;
  background-color: blue;
}

.circle_css {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background-color: green;
}

.shapeText {
  padding-top: 30%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<html lang="en">

<head>
  <link rel="stylesheet" type="text/css" href="<?php echo URL; ?>views/index/css/index_Main.css" />
</head>

<body>

  <div>
    <input type="button" id="moveSquare" value="Move Square" />
  </div>

  <div>
    <input type="button" id="moveCircle" value="Move Circle" />
  </div>

  <div id="square" class="square_css">
    <div id="squareText" class="shapeText"></div>
  </div>

  <div id="circle" class="circle_css">
    <div id="circleText" class="shapeText"></div>
  </div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script type="text/javascript" src="<?php echo URL; ?>views/index/js/index_main.js"></script>
</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

Unveiling and Shifting Among Concealed HTML Forms

After going through numerous tickets with similar questions, I still can't seem to achieve what I want. So, I have no choice but to ask this question myself. I currently have an HTML page with 2 forms and 2 buttons. Both forms are initially hidden us ...

initiate changes to the application's style from a component nested within the app

I'm looking to update the background color of the entire page, including the app-nav-bar, when I'm inside a child component. When I navigate away from that component, I want the default style to be restored. Any suggestions on how to achieve this ...

Is it possible to directly update the label text in AngularJS from the view itself?

I found the following code snippet in my HTML <span ng-class="newProvider ? 'newProvider' : ''" class="help-block"> {{ 'new-product.provider.helper' | locate }} </span> Whenever newProvider is se ...

How can I make two flexbox items in a row stack on top of each other as a column?

I'm currently working on a layout that involves a parent flexbox containing multiple sections. My challenge lies in getting two specific sections to stack vertically while the rest of the layout remains horizontal. At the moment, I have two sections ...

How can I change an element using jQuery's getElementById method?

My current setup involves using a web page as a server and an Arduino as a client. Whenever a specific mode is active, the Arduino sends the following code: <LED>on</LED> The server then adjusts its status accordingly based on this input. I ...

where is the yarn global registry located?

After updating yarn to point to my custom registry and verifying the changes, here is what I found: $yarn config list -g yarn config v1.22.10 info yarn config { 'version-tag-prefix': 'v', 'version-git-tag': true, ' ...

Using jQuery flot to create various time charts

I'm trying to combine the visitor count data from this month (chart 1) and last month (chart 2) into a single chart using Flot. While I've successfully created chart 1, I'm facing challenges in overlaying it with chart 2 due to the x-axis pa ...

What is the best way to convert $('input[type=text]') into vanilla JavaScript?

How can I change this to plain JavaScript? I've been struggling to find a solution, any pointers? ...

Advancing the utilization of custom Angular input fields

I've developed a unique Angular input element that utilizes a textarea as its primary input field. Is there a way for me to pass along the enter key event to the main form? ...

Is there a way to emulate synchronous behavior in JavaScript?

var routeSearch = new MyGlobal.findRoutes({ originPlaceId: search.placeInputIds.originPlaceId, destinationPlaceId: search.placeInputIds.destinationPlaceId, directionsService: search.directionsService, directionsDisplay: sear ...

Struggling to pinpoint the exact element in Python/Selenium

As I work on creating a website manipulation script to automate the process of email mailbox creation on our hosted provider, I find myself navigating new territory in Python and web scripting. If something seems off or subpar in my script, it's beca ...

When using PHP's `json_encode()`, don't forget to append a "1" at the

While utilizing json_encode in my project, I have encountered an issue that is perplexing. On one particular page where I make an ajax call, the resulting json seems to mysteriously add a 1 to the end of the string. The output of my return string appears ...

Type of variable that is not an array

I need a quick way to check if a value is an object {} but not an array []. The code I currently have is: function isPlainObject(input) { return !Array.isArray(input) && typeof input === 'object'; } Is there a more concise method to a ...

Replacing variables in a function: A step-by-step guide

I have frequently used the replace function to eliminate classes in JavaScript. Currently, I am working on creating a JavaScript function that allows me to remove a specific class from an element by passing in the element and the class name. changeAddress ...

How can I incorporate a spinning cog from Font Awesome into a jQuery click event?

I am looking to incorporate a spinning font awesome cog while the data is being fetched and remove it once the process is complete. Here is the HTML snippet that needs to be inserted: <i class="fa fa-spin fa-cog"></i> And this is the accompa ...

Ajax calls within nested functions are not being executed in the correct sequence

Currently, I am utilizing the geonames API to retrieve geographical information. My objective is to extract the names of states within a country using the getStateInfo function and subsequently obtain a list of cities in each state through the getCityInfo ...

Displaying a Next.js component depending on the environment setting

Having trouble displaying a maintenance message to users based on an environment value. In my .env.local file, I have the following value set: NEXT_PUBLIC_SHOW_MAINTENANCE=true This is how my page is structured: const Index = () => { const showMai ...

Identifying the FireOS version using JavaScript

Can JavaScript be used to determine the version of FireOS that a Kindle device is running when accessing your website? ...

Mobile devices do not support internal link scrolling in Material UI

Currently, I'm utilizing internal links like /lessons/lesson-slug#heading-slug for smooth scrolling within a page. While everything functions perfectly on desktop, it ceases to work on mobile view due to an overlaid drawer nav component. Take a look a ...

"Exploring the Differences between JavaScript, AJAX, and Servlet for String

I am attempting to compare a string that is received from a servlet. The servlet page returns the following: out.println("pass"); In JavaScript: function Check() { if (ajax.responseText === "pass") { document.getElementById("pass").innerHTML = "This is ...