JavaScript Animation Mastery

I attempted to move the small yellow box within the larger red box in all directions endlessly. Although I successfully moved it to the right and bottom, I encountered issues moving it to the left and top. Despite using Visual Studio Code, I couldn't resolve the problem. Can anyone help me with the Javascript code for this task?

 window.onload = function(){
                var posX = 0,posY = 0, posZ=0;
                var smallbox = document.getElementById("smallbox");
                var time = setInterval(move,10);
    
                function move(){
                    if(posX>=150){
                       if(posY>=150){
                            if(posZ>=150){
                                clearInterval(time);
                            }
                            else{
                                posZ++;
                                smallbox.style.right = posZ + "px";
                            }
                        }
                        else{
                            posY++;
                            smallbox.style.top = posY + "px";
                        }
                    }
                    else{
                        posX = posX+1;
                        smallbox.style.left = posX + "px"; 
                    }
                }
            }
        #bigbox{
            height: 200px;
            width: 200px;
            background-color: red;
            position: relative;
        }
        #smallbox{
            height: 50px;
            width: 50px;
            background-color: yellow;
            position: absolute;
        }
<div id="bigbox">
   <div id="smallbox">
    
   </div>
</div>

Answer №1

If your animation isn't functioning properly, it could be due to using CSS alignments that require either "top" or "bottom" and "left" or "right" for proper alignment of objects. It seems like you may be attempting to align horizontally using "left" and then trying to align horizontally using "right", essentially cancelling each other out.

Instead, I recommend using code that follows this logic:

if at top-left, move right.
if at top-right, move down.
if at bottom-right, move left.
if at bottom-left, move up.

An illustration of this concept in action can be seen below:

window.onload = function() {
  var posX = 0,
    posY = 0,
    boxW = 200,
    boxH = 200,
    smallboxW = 50,
    smallboxH = 50;
  var smallbox = document.getElementById("smallbox");
  var time = setInterval(move, 10);

  function move() {
    if (posY <= 0 && posX < boxW) {
      // go right
      posX++;
      smallbox.style.left = posX + "px";
    }
    if (posX >= boxW - smallboxW && posY < boxH) {
      // go down
      posY++;
      smallbox.style.top = posY + "px";
    }
    if (posY >= boxH - smallboxH && posX > 0) {
      // go left
      posX--;
      smallbox.style.left = posX + "px";
    }
    if (posX <= 0 && posY > 0) {
      // go up
      posY--;
      smallbox.style.top = posY + "px";
    }
  }
}
#bigbox {
  height: 200px;
  width: 200px;
  background-color: red;
  position: relative;
}

#smallbox {
  height: 50px;
  width: 50px;
  background-color: yellow;
  position: absolute;
}
<body>
  <div id="bigbox">
    <div id="smallbox">

    </div>
  </div>
</body>

Answer №2

Enhance your coding experience by leveraging the capabilities of CSS within JavaScript using Element.animate().

With this feature, you can easily pause and resume animations as needed.

const smallbox = document.querySelector('#smallbox');

smallbox.animate([
  // keyframes
  {
    transform: 'translate(150px, 0px)'
  },
  {
    transform: 'translate(150px, 150px)'
  },
  {
    transform: 'translate(0px, 150px)'
  },
  {
    transform: 'translate(0px, 0px)'
  },
  {
    transform: 'translate(150px, 0px)'
  },
], {
  // timing options
  duration: 2000,
  iterations: Infinity
});
#bigbox {
  height: 200px;
  width: 200px;
  background-color: red;
  position: relative;
}

#smallbox {
  height: 50px;
  width: 50px;
  background-color: yellow;
  position: absolute;
}
<div id="bigbox">
  <div id="smallbox">

  </div>
</div>

Answer №3

Using the CSS keyframes for animation is a viable alternative.

#bigbox {
  height: 200px;
  width: 200px;
  background-color: red;
  position: relative;
}

#smallbox {
  height: 50px;
  width: 50px;
  background-color: yellow;
  position: relative;
  animation: move-around 4s infinite linear;
}

@keyframes move-around {
  0% {
    left: 0;
    top: 0;
    transform: translate(0%, 0%);
  }
  25% {
    left: 100%;
    top: 0;
    transform: translate(-100%, 0%);
  }
  50% {
    left: 100%;
    top: 100%;
    transform: translate(-100%, -100%);
  }
  75% {
    left: 0;
    top: 100%;
    transform: translate(0%, -100%);
  }
  100% {
    left: 0;
    top: 0;
    transform: translate(0%, 0%);
  }
}
<body>
  <div id="bigbox">
    <div id="smallbox">

    </div>
  </div>
</body>

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

Crafting numerous CSS templates

I am currently working on creating multiple boxes or templates (5 on each row) from a movie API. I have successfully retrieved all the necessary data and do not require a responsive design. https://i.sstatic.net/CNz9R.png The issue arises when I attempt ...

Is there a way to retrieve a comprehensive list of all the potential routes in my nuxt.js project?

Is there a way to retrieve a list of all the potential routes in my nuxt.js project? (this would include all URLs) ...

Tips for preventing divs from sliding to the next row when adding margin in Bootstrap

{% for plant in plants %} {% if forloop.counter0|divisibleby:3 %} <div class="row row-cols-3"> {% endif %} {% include 'included/_plant_cell.html' %} {% if forloop.counter|divisibleby:3 %} </div&g ...

Error in Mocha test: Import statement can only be used inside a module

I'm unsure if this issue is related to a TypeScript setting that needs adjustment or something else entirely. I have already reviewed the following resources, but they did not provide a solution for me: Mocha + TypeScript: Cannot use import statement ...

The Angular $http.jsonp() function can only be executed one time

Upon the first response being successful (alert->done), any subsequent hits will result in an 'error' response. I attempted to resolve this issue by adding some config parameters with 'cache: false', but it still only works the firs ...

Sending a blob object via Websocket on a remote server and a string on a local server

I'm a newcomer to Ubuntu and recently started working on a project that involves WebSocket functionality. While everything runs smoothly on my local server, I encounter the following error on the live server: Uncaught SyntaxError: Unexpected token ...

Seeking particular section of online content in an asynchronous manner

Is there a method for asynchronously requesting a specific portion of a web resource (like the initial 100 bytes) using JavaScript? I believed this could be accomplished through XmlHttpRequest by adjusting its Range header. However, if the server utilizes ...

What is the best way to have text fit perfectly into a table cell?

In my asp.net table, the first column contains captions for each row of data. The length of these captions varies, with different amounts of words in each one. I am looking to align the first letters of each caption at the beginning edge of the cells (left ...

Display HTML content generated by JavaScript in the page source

Can the HTML elements I've added through JavaScript and jQuery codes be displayed in the page source (ctrl+U)? ...

What are the best practices for utilizing "async/await" and "promises" in Node.js to achieve synchronous execution?

I'm fairly new to the world of web development and still grappling with concepts like promises and async/await. Currently, I'm working on a project to create a job posting site, but I've hit a roadblock trying to get a specific piece of code ...

What is the best way to change the name of a property within an object

I need to update the names of properties in a nested object. { 0: {value: "can_view"}, 1: {value: "can_create"} } The desired output should be: { user_can: "can_view", user_view: "can_create" } ...

securely managing file access through lockfile.locksync in node.js

Currently, I am utilizing lockfile.locksync to secure a file in my node.js application. However, I am interested in understanding the inner workings of this utility in more detail. Despite multiple resources referring to it as a "very polite lock file util ...

Determine the number of network requests being made on a webpage

In my quest to develop a universal method using selenium, I am seeking a way to ensure that all background network activities, including Ajax, Angular, and API calls, have completed. While I am aware of the option to determine the number of active Ajax cal ...

Exploring ways to animate a conditionally displayed component when the state changes using a combination of javascript and css

I am encountering a scenario where I have a react component with a specific part that is rendered conditionally. Upon clicking on a visible element within the component (button), the state changes triggering the display of the hidden parts. However, inst ...

CSS problem: Footer encroaching on the content above

For more information, please visit this link When the window is minimized, the footer overlaps the content above it. Despite spending hours trying to fix this issue, I have not been successful. View when maximized: here View when minimized: here Even af ...

The Axios.get function is mistakenly returning raw HTML instead of the expected JSON data

I'm new to using react js and am currently attempting to retrieve data from the database by utilizing axios.get within the componentDidMount lifecycle method. The code snippet below shows how I am trying to fetch products. My setup involves using reac ...

"Stuck in a Standstill: Express/React Commit

Currently, I have set up an Express backend server on port 5000 along with a React frontend running on port 3000. My goal is to fetch some data from an Express post route and return it to the frontend, however, I am encountering an issue where my Promise n ...

Attach the Bootstrap-Vue modal to the application's template

I am implementing a custom modal using bootstrap-vue modal in my project on codesandbox. This is the template structure: <template> <b-button variant="link" class="btn-remove" @click="removeItemFromOrder(index)"> Remove item </b-bu ...

Adjusting div to not be absolutely positioned

Trying to create a div with animated borders, but it only works when positioned absolutely in the center. For illustration, here is the HTML and CSS code: .bb, .bb::before, .bb::after { position: absolute; top: 0; bottom: 0; left: 0; right: 0; ...

Issue with TypeScript in Vue3: Unable to access computed property from another computed property

In my Vue3 project with TypeScript, I am encountering an issue where I am unable to access the properties of the returned JavaScript object from one computed property in another computed property using dot notation or named indexing. For instance, when tr ...