Hello, i’m trying to learn some js animations. I copied some source code from w3schools that makes a rectangle (the animate div) travel diagonally right across a larger rectangle (container div). Here is the original code:
<!DOCTYPE html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
</style>
<body>
<p>
<button onclick="myMove()">Click Me</button>
</p>
<div id ="container">
<div id ="animate"></div>
</div>
<script>
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';
}
}
}
</script>
</body>
</html>
But the problem is, i want to make a second block going in the opposite corner and make them crossover each other, but i cant get the other block to move for some reason. I’m very new to js, so apologies if it’s obvious.
This is what i tried:
<!DOCTYPE html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
#animate2 {
width: 50px;
height: 50px;
position: absolute;
background-color: blue;
}
</style>
<body>
<p>
<button onclick="myMove(); myMove2();">Click Me</button>
</p>
<div id ="container">
<div id ="animate"></div>
<div id ="animate2"></div>
</div>
<script>
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 = 0;
var id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.bottom = pos + 'px';
elem.style.right = pos + 'px';
}
}
}
</script>
</body>
</html>
Edit: i got the other block to move with this code, but now the problem is both of the squares are in the top left corner in the beginning when i need them be start at opposite corners and end at opposites