Learn how to create animations using JavaScript
Here’s a solution with code for creating animations using JavaScript, along with meta title, description, and tags:
HTML, CSS, and JavaScript Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Learn how to create animations using JavaScript. This simple tutorial shows how to move an element on the screen using basic animation techniques.">
<meta name="keywords" content="JavaScript, animations, tutorial, web development, move element, animation tutorial, basic animation, HTML, CSS">
<meta name="author" content="Your Name">
<title>Learn how to create animations using JavaScript</title>
<style>
#myContainer {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#myAnimation {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
</style>
</head>
<body>
<p>
<button onclick="myMove()">Click Me</button>
</p>
<div id="myContainer">
<div id="myAnimation"></div>
</div>
<script>
var id = null;
function myMove() {
var elem = document.getElementById("myAnimation");
var pos = 0;
clearInterval(id);
id = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}
</script>
</body>
</html>
Explanation of the JavaScript:
-
var id = null;: This is used to store the reference to thesetIntervalfunction so that it can be cleared later if needed (for example, to stop the animation). -
function myMove(): This function is called when the user clicks the button. It performs the animation.-
var elem = document.getElementById("myAnimation");: This gets a reference to the#myAnimationdiv (the red square). -
var pos = 0;: This variable keeps track of the position of the element during the animation. It starts at 0. -
clearInterval(id);: This clears any previous animation intervals to ensure that the animation does not stack up if the button is clicked multiple times in quick succession. -
id = setInterval(frame, 10);: ThesetInterval()function calls theframefunction every 10 milliseconds, creating a smooth animation. Theframefunction moves the element by incrementingpos.
-
The frame() function:
-
if (pos == 350): Once theposvariable reaches 350, it stops the animation. -
pos++: Increases theposby 1 on each call of theframefunction. -
elem.style.top = pos + 'px'; elem.style.left = pos + 'px';: These lines move the element by setting itstopandleftproperties. The element moves both downward (top) and to the right (left) by increasing theposvalue. This results in a diagonal movement. -
clearInterval(id);: Stops thesetInterval()once theposreaches 350px. This stops the element from moving.