Continuously running a JavaScript animation loop without interruption

How can I create a continuous loop for an animation? To better illustrate my question, please refer to the example on W3Schools where a box moves from top to bottom and then halts.

http://www.w3schools.com/js/tryit.asp?filename=tryjs_dom_animate_3

I am struggling to find out how to ensure this box animation repeats endlessly. In other words, once it reaches the bottom, it should return to its starting point and continue the animation indefinitely.

Answer №1

Here are some ways to modify the JS code:

var element = document.getElementById("animate");
var position = 0;
var identifier = setInterval(moveFrame, 10);

function moveFrame() {
  if (position == 150) { position = 0; }
  position++;
  element.style.top = position + 'px';
  element.style.left = position + 'px';
}
#container { width: 200px; height: 200px; position: relative; background: yellow; } #animate { width: 50px; height: 50px; position: absolute; background-color: red; }
<div id ="container">
  <div id ="animate"></div>
</div>

Answer №2

Replace the clearInterval(id); command, which stops the animation timer, with pos = 0; to reset the box's position every time it reaches a corner.

Answer №3

Modify the script as shown below to prevent it from pausing. The use of 'runAlready' is necessary to control the appearance of the second rectangle, and setting pos=0 within the if statement positions the rectangle at the top left corner.

let run = false;
function moveElement() {
  if(!run) {
    run = true;
    let element = document.getElementById("animate");   
    let position = 0;
    let animationId = setInterval(moveFrame, 5);
    function moveFrame() {
      if (position == 350) {
        position = 0;
      } else {
        position++; 
        element.style.top = position + 'px'; 
        element.style.left = position + 'px'; 
      }
    }
  }
}

Answer №4

Utilizing the setInterval(frame, 5) function instructs the program to execute the frame() function every 5 milliseconds, resulting in the creation of an animation.

On the other hand, when the clearInterval(id) function is invoked, it halts the ongoing animation.

An intriguing addition has been made below. By introducing a variable called 'direction,' the code alters the box's movement direction. Instead of bringing the animation to a stop once the box reaches the lower right corner, it switches the direction and continues its path.

function myMove() {
  var elem = document.getElementById("animate");   
  var pos = 0;
  var id = setInterval(frame, 5);
  var direction = 1;
  function frame() {
    if (pos == 0){
        direction = 1;
    } else if(pos == 350){
        direction = -1;
    }
    pos += direction; 
    elem.style.top = pos + 'px'; 
    elem.style.left = pos + 'px'; 
  }
}

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

Having difficulty modifying CSS font classes

This marks the beginning of a website I am currently creating for a client. Check it out here Here's the issue. I initiated this project some time back and upon returning to it, I'm facing difficulty in changing font styles without using inline ...

Error encountered while trying to access "toast" element using "$(...)"

Currently, I'm in the process of developing a web app using Django Channels and WebSockets. My goal is to dynamically generate Bootstrap toasts (https://getbootstrap.com/docs/4.2/components/toasts/) when a WebSocket connection is established. However, ...

Transmitting intricate Javascript Array to ASP.NET Controller Function

I am facing an issue with sending a complex JavaScript array to my asp.net mvc6 controller method. I have tried two different methods to pass the data, but neither seem to be working for me. public IActionResult TakeComplexArray(IList<ComplexArrayInfo ...

Pressing the button inside the iframe will cause the div to appear in the parent

I have a button in my iframe that opens a div on the same page: <li> <input type='button' id='hideshow2' class='radiobutton' value='Core' onclick="showDiv('#content2')"> </li> <di ...

Find items where a certain value matches any of the values in another array and return them

I'm seeking assistance with a specific task. I have an object structured as shown below: SOMEKEY: { "key1": val1, "key2": val2 } Additionally, I have an array that contains string values like this: [stringA, stringB, stringC ...

Ways to obtain the index of a button

Once upon a time, I used to create a plethora of buttons using a for loop. The title[] array was filled with numerous values. export const renderButtons1 = (numOfBtns,title,navigate) => { const views1 = []; for ( var i = 0; i < numOfBtns; ...

What steps can I take to ensure that my React child components will render successfully, even if a prop is absent

TLDR; Seeking solution to render child components in React even if a property of this.props is missing. My React app utilizes Yahoo's Fluxible and fetches data from a Wordpress site using WP REST API. Sometimes, the API may return incomplete data cau ...

Could someone kindly clarify the workings of this jQuery script for me?

I found this code online, but I'm struggling to comprehend its functionality. In order to make any edits for my needs, I need to understand how it operates. The purpose of this script is to close a panel with an upward slide animation when the "x" but ...

The functionality of the submit form is encountering issues upon integration of Ajax requests

Hello everybody! I am currently creating a dynamic form for editing specific classes, but I am facing an issue with the ajax call not working. Below is the HTML code for the form: <form id="userDataForm" name="userDataForm" th:acti ...

The grpc client is not able to receive the data being streamed from the

I've been attempting to stream the output of a nodejs child process through grpc, but I consistently receive an empty result. Here is my proto file: syntax = "proto3"; package servicePackage; service Mobile { rpc sign(Empty) returns ( ...

Refreshing Vue by reloading new components and injecting them into the HTMLDOM

Is there a way to make Vue re-initialize itself after inserting a component fetched from an API into the DOM? The component looks like this: <div><My_component /></div> This component is part of a back-end snippet. When inserting it i ...

What is the best way to give precedence to non-auto capitalization in input fields on the Input Component from Material UI, especially when using iPads?

The issue I'm encountering is specific to Material UI and IPad, requiring a change in the component used from MUI. Currently, I am utilizing the Input component from Material UI. Upon clicking on the input, the IPad keyboard opens and automatically ...

Searching for mobile WiFi preferences through a web browserHere are the steps to

Is there a method to access mobile connectivity settings through a website? I am interested in determining the connection type (3G\4G\WiFi) and if it is WiFi, identifying the security method being used. Is this achievable? If so, how? Edit: If ...

The req.body variable is not defined in this context, which means only the default MongoDB id is

I've been attempting to utilize a post request for inserting data into MongoDB using Mongoose, but I keep encountering an issue where req.body is undefined. The document gets inserted into the database, but only the default Object ID is included. Thi ...

Creating an Angular JS controller that utilizes a filter for a JSON array of objects

I have the following JSON data and I'm trying to determine the number of objects with Status: 1 in the JSON. The approach I've taken so far is not working. I understand that ng-filter should only be applied to Arrays, but I'm struggling to ...

Disabling the movement of arrows in the client-testimonials-carousel plugin

This plugin that I'm currently using is working flawlessly: However, I'm unsure about how to make the arrows stationary and prevent them from moving. Currently, they are centering themselves based on the height of the div, but I want them to rem ...

Tap to reveal additional information with the power of Jquery and ajax

I have a question regarding the popup slide functionality. I would like to achieve the following: Currently, I am using the following code to display post details upon clicking: function getPostDetails(id){ var infoBox = document.getElementById("in ...

What is the best way to successfully navigate a parsed document?

Hey there, I appreciate your time and assistance. I am currently working on parsing an XML file located in the "res/raw" folder and passing the parsed result to another class for further processing. However, I seem to be stuck and unable to find a solution ...

Refresh jQuery DataTable with updated search results

I have a function that loads the DataTable once the document is loaded. $(document).ready(function() { var $dataTable = $('#example1').DataTable({ "ajax": 'api/qnams_all.php', "dataType": "json", "bDestroy": true, "s ...

What is causing my cookie script to malfunction?

I'm experiencing an issue with my cookie script on the following website: Upon visiting my site, you'll come across a hidden <div id="popupDiv"> Due to the display: none property in the CSS, it's not visible as intended. However, it ...