Is there a way I can finish animating these divs in a diagonal motion?

I successfully made the blue and red divs move diagonally and switch positions. Now I am looking to achieve the same effect with the green and pink divs using a similar function.

I am unsure about setting the position of both divs to 0 and 350 for those particular elements.

I want the green div to move towards the location of the pink div

function click_move() {
  myMove();
  myMove2();
  myMove3();
  myMove4(); 
}


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

function myMove2() {
  var elem = document.getElementById("animate2");   
  var pos = 350;
  var id = setInterval(frame2, 5);
  function frame2() {
    if (pos == 0) {
      clearInterval(id);
    } else {
      pos--; 
      elem.style.top = pos + 'px'; 
      elem.style.left = pos  + 'px';
    }
  }
}
button{
 position:fixed;
  left: 500px;
  top:  100px;}

#container {
  width: 400px;
  height: 400px;
  position: fixed; 
  background: yellow;
  top:0px;
  left:0px;
}
#animate {
  width: 50px;
  height: 50px;
  position: fixed;  
  background-color: red;
  top:0px;
  left:0px;
}

#animate2 {
  width: 50px;
  height: 50px;
  position: fixed;  
  background-color: blue;
  top:350px;
  left:350px;
}

#animate3 {
  width: 50px;
  height: 50px;
  position: fixed;  
  background-color: green;
  top: 0px;
  left:350px;
}

#animate4 {
  width: 50px;
  height: 50px;
  position: fixed;  
  background-color: pink;
  top: 350px;
  left:0px;
}
<html>
<body>
<p>
<button onclick="click_move()">Click Me</button>
</p> 
<div id ="container">
<div id ="animate"></div>
<div id ="animate2"></div>
<div id ="animate3"></div>
<div id ="animate4"></div>
</div>


</body>
</html>

Moving forward, I want the pink div to take the place where the green div is currently positioned.

Answer №1

After some trial and error, I managed to figure it out on my own by taking a longer route in breaking up the function.

function click_move() {
  myMove();
  myMove2();
  myMove3();
  myMove4(); 
  myMove5();
  myMove6();
}


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

function myMove2() {
  var elem = document.getElementById("animate2");   
  var pos = 350;
  var id = setInterval(frame2, 5);
  function frame2() {
    if (pos == 0) {
      clearInterval(id);
    } else {
      pos--; 
      elem.style.top = pos + 'px'; 
      elem.style.left = pos  + 'px';
    }
  }
}

function myMove3() {
  var elem = document.getElementById("animate3");   
  var pos = 0;
  var id = setInterval(frame3, 5);
  function frame3() {
    if (pos == 350) {
      clearInterval(id);
    } else {
      pos++; 
      elem.style.top = pos + 'px'; 
    }
  }
}

function myMove4() {
  var elem = document.getElementById("animate3";  
  var pos = 350;
  var id = setInterval(frame3, 5);
  function frame3() {
    if (pos == 0) {
      clearInterval(id);
    } else {
      pos--; 
      elem.style.left = pos + 'px'; 
    }
  }
}

function myMove5() {
  var elem = document.getElementById("animate4");   
  var pos = 350;
  var id = setInterval(frame4, 5);
  function frame4() {
    if (pos == 0) {
      clearInterval(id);
    } else {
      pos--; 
      elem.style.top = pos + 'px'; 
    }
  }
}

function myMove6() {
  var elem = document.getElementById("animate4";  
  var pos = 0;
  var id = setInterval(frame4, 5);
  function frame4() {
    if (pos == 350) {
      clearInterval(id);
    } else {
      pos++; 
      elem.style.left = pos + 'px'; 
    }
  }
}
button{
 position:fixed;
  left: 500px;
  top:  500px;}

#container {
  width: 400px;
  height: 400px;
  position: fixed; 
  background: yellow;
  top:0px;
  left:0px;
}
#animate {
  width: 50px;
  height: 50px;
  position: fixed;  
  background-color: blue;
  top:0px;
  left:0px;
}

#animate2 {
  width: 50px;
  height: 50px;
  position: fixed;  
  background-color: pink;
  top:350px;
  left:350px;
}

#animate3 {
  width: 50px;
  height: 50px;
  position: fixed;  
  background-color: red;
  top: 0px;
  left:350px;
}

#animate4 {
  width: 50px;
  height: 50px;
  position: fixed;  
  background-color: green;
  top: 350px;
  left:0px;
}
<html>
<body>
<p>
<button onclick="click_move()">Click Me</button>
</p> 
<div id ="container">
<div id ="animate"></div>
<div id ="animate2"></div>
<div id ="animate3"></div>
<div id ="animate4"></div>
</div>


</body>
</html>

Answer №2

It's interesting how the main concept remains consistent! The first two functions only require a 'pos' variable because the left and top values are the same for red and blue during the animation. This allows you to manipulate them using a single variable like 'pos'!

However, for the other two divs, left and top values are different, so they need to be specified separately.

function myMove3() {
  var elem = document.getElementById("animate3");   
  var left = 350;
  var top = 0;
  var id = setInterval(frame3, 5);
  function frame3() {
    if (left == 0) {
      clearInterval(id);
    } else {
      left--; 
      top++;
      elem.style.top = top + 'px'; 
      elem.style.left = left  + 'px';
    }
  }
}

function myMove4() {
  var elem = document.getElementById("animate4");   
  var left = 0;
  var top = 350;
  var id = setInterval(frame4, 5);
  function frame4() {
    if (left == 350) {
      clearInterval(id);
    } else {
      left++; 
      top--;
      elem.style.top = top + 'px'; 
      elem.style.left = left  + 'px';
    }
  }
}

Answer №3

When utilizing HTML elements styled with CSS instead of a <canvas>, it is advisable to employ CSS and its transition-property for smoothly transitioning between two positions.

The benefits of using CSS over JS in this scenario are:

  1. CSS offers a straightforward property to achieve the desired effect
  2. CSS aims to generate frames with minimal latency
  3. CSS consumes less RAM compared to JS (since transition is optimized for this purpose)
  4. The transition can be toggled midway through effortlessly
  5. Liberates the callstack of JS, allowing other functions to execute seamlessly
  6. Requires minimal JS involvement

To simplify the process, I utilized CSS custom properties to specify the size of the squares being moved, referencing them using var() when needed.
I labeled mine as --span-size.

Since our aim is to position the squares in the corners of their parent element, we can easily calculate the desired locations:
Note that the origin of an HTML element is its top-left corner.

  • Top-left: top: 0% left: 0%
  • Top-right: top: 0%
    right: calc(100% - var(--span-size))
  • Bottom-left:
    top: calc(100% - var(--span-size))
    left: 0%
  • Bottom-right:
    top: calc(100% - var(--span-size))
    right: calc(100% - var(--span-size))

By using the appropriate selectors, we can toggle between the two states by adjusting a class of the parent element (I used .toggled).
In the CSS, we simply define the initial and final values we desire, along with the duration of the transition.

document.querySelector('button').addEventListener('click', function() {
  const div = document.querySelector('div');
  div.classList.toggle('toggled');
});
body {
  display: flex;
  align-items: center;
  gap: 1rem;
}

div {
  position: relative;
  border: 1px solid black;
  width: 200px;
  height: 200px;
  background: yellow;
}
span {
  --span-size: 32px;
  
  position: absolute;
  width: var(--span-size);
  height: var(--span-size);
  transition: 1s linear;
}

#s1 {
  top: 0%;
  left: 0%;
  background: red;
}
#s2 {
  top: 0%;
  left: calc(100% - var(--span-size));
  background: green;
}
#s3 {
  top: calc(100% - var(--span-size));
  left: 0%;
  background: blue;
}
#s4 {
  top: calc(100% - var(--span-size));
  left: calc(100% - var(--span-size));
  background: pink;
}

div.toggled #s1 {
  top: calc(100% - var(--span-size));
  left: calc(100% - var(--span-size));
}
div.toggled #s2 {
  top: calc(100% - var(--span-size));
  left: 0%;
}
div.toggled #s3 {
  top: 0%;
  left: calc(100% - var(--span-size));
}
div.toggled #s4 {
  top: 0%;
  left: 0%;
}
<div>
  <span id="s1"></span> <!-- 'sX' for 'span-ID', for easier selection -->
  <span id="s2"></span>
  <span id="s3"></span>
  <span id="s4"></span>
</div>
<button>Toggle state!</button>

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

Mastering the art of extracting elements from an HTML Dygraph

Attempting to extract all data points from this particular website utilizing BeautifulSoup and requests in Python. The current code in progress is as follows: session = requests.Session() page = session.get(https://bitinfocharts.com/comparison/bitcoin-tra ...

Combining two objects retrieved using ngResource in AngularJS

Seeking guidance on merging two objects retrieved using ngressource. Every 5 seconds, I invoke my service to fetch a message and aim to append the new message with the older ones. The JSON message I receive: [ {"age": 0,"id": "my first tweet","name": "H ...

What could be causing this code to malfunction on jsfiddle?

Why doesn't this code from W3schools work on jsfiddle? I tried to implement it here: https://jsfiddle.net/u6qdfw5f/ <!DOCTYPE html> <html> <title>W3.CSS</title> <meta name="viewport" content="width=device-width, initial ...

Trigger a child-mounted event and retrieve it from the parent component

Imagine I have a component named child. There is some data stored there that I need to retrieve in the parent component. To accomplish this, I plan to emit an event in the childs mount using this.$emit('get-data', this.data), and then receive it ...

Creating a responsive grid layout with HTML and CSS

Is there a way to adjust the grid layout so that the second row of blocks align just below the corresponding block above instead of creating an entirely new row? http://jsfiddle.net/AndyMP/wSvrN/ body { margin-left: 0px; margin-top: 0px; marg ...

Collaborate on sharing CSS and TypeScript code between multiple projects to

I am looking for a solution to efficiently share CSS and TS code across multiple Angular projects. Simply copy-pasting the code is not an ideal option. Is there a better way to achieve this? ...

What steps are involved in integrating Element Plus with Nuxt 3?

Seeking assistance with installing Element Plus in Nuxt 3. I followed the instructions from the official Element Plus documentation, but despite adding unplugin-vue-components, unplugin-auto-import, and adjusting webpack settings in the nuxt config file, ...

Concealing unnecessary borders on list elements using jQuery

Here is the code I am working with: http://jsfiddle.net/eLyJA/ I am looking to calculate and eliminate all border edges to achieve this visual effect: ...

Attempting to dynamically link my "ng-true-value" in AngularJS

Working with values retrieved from a database, my goal is to include a checkbox, load the description, and provide 2 text boxes – one editable and the other read-only. Both text boxes initially display values from the database. When the checkbox is chec ...

Troubleshooting $digest problems with AngularJS and the selectize directive

I am encountering difficulties when utilizing the watch function within a directive in conjunction with a third-party plugin named selectize. Despite researching extensively about $digest and $watch, I am still facing issues. Although my example below is ...

Exploring the isolated scopes of AngularJS directives

Exploring directives in AngularJS led me to this interesting code snippet: var app = angular.module('app', []); //custom directive creation app.directive("myDir", function () { return { restrict: "E", scope: { title: '@ ...

Enhancing my code by implementing various conditions in React

Looking for ways to enhance my code quality (Very Important, Important, Medium, Low, Good, Excellent,...) : { Header: "Opinion", accessor: (row) => row.opinion, Cell: props => <span> {props.value == ...

What is the best way to run a scheduled task automatically using node-cron?

I have a custom function that saves data to the database using the POST method. When testing it with Postman, I send an empty POST request to trigger the controller. Upon execution, the function triggers two more functions. One of them is responsible for ...

What is the best way to ensure all asynchronous tasks are completed in Node.js before proceeding?

My program is in need of running numerous asynchronous tasks. Additionally, there needs to be a task that will only run once all the other asynchronous tasks have completed. Is there a way I can create a function that waits for all async functions to fin ...

Animating a dotted border path in SVG for a progress bar effect

I am attempting to create an animation for a dotted SVG circle that resembles a progress bar, where it fills itself over a duration of 3 seconds. However, I am facing difficulties in achieving this effect with the dotted border. The current code I have doe ...

Fuel Calculation - Unable to pinpoint the error

My JavaScript Code for Calculating CO2 Emissions I'm working on a program that calculates how much CO2 a person produces per kilometer. This is part of my school project and I'm still learning, so please bear with me... I also just signed up on ...

Is it possible to have unique color tags in Material UI Autocomplete?

I'm currently diving into the world of material-ui and encountering some challenges that I could use help with. I am trying to incorporate multiple arrays into the autocomplete menu (e.g., options={top100Films, top100Shows}, but with the correct sy ...

Angular 8 fails to retain data upon page refresh

I have a property called "isAdmin" which is a boolean. It determines whether the user is logged in as an admin or a regular user. I'm using .net core 2.2 for the backend and Postgre for the database. Everything works fine, but when I refresh the page, ...

Footer panel in Bootstrap not aligning to the bottom of the page

I'm experiencing an issue with my footer getting stuck in the middle of the page. Strangely, this problem only occurs on one specific page, and not on any other pages. I've tried various methods to fix it, but none of them have been successful. ...

How to accentuate search results using Angular filters and conceal non-matching text?

Recently, I came across an interesting example of using Angular filter to highlight search results. It works well in highlighting the word 'suit', but I noticed that all non-matching text remains visible. If you'd like to see the example I ...