JavaScript is a versatile programming language for front-end development that powers dynamic interactions on websites.
Using JavaScript for animation can enhance the visual appeal of your projects. It enables you to manipulate HTML and CSS elements with ease, creating smooth transitions and interactive movements.
Unlike static images, animations can draw users’ attention, making your page much more lively and engaging.
Furthermore, JavaScript animations can be more responsive to user interactions compared to pre-rendered animations.
If you’re new to JavaScript, don’t worry! We will, as simply as possible, show you how to integrate Javascript into your HTML Documents and create your first animation.
Create your first animation with Javascript
To create your first animation using JavaScript, we will follow a simple yet effective example that involves moving an element across the screen.
This example will introduce basic concepts such as selecting elements, manipulating their properties, and using JavaScript methods to create smooth animations.
First, we need an HTML element to animate. For illustration, let’s create a simple `div` with a class name of `box`. Here’s how it looks:
<div class="box"></div>
Open your HTML document, and insert the above code within the <body> tag. It should be like the one below:
Next, we’ll style the box using CSS. Assign it dimensions, a background colour, and an initial position. To do this, we’ll make use of the class name.
We also add the CSS Animation effect so the Javascript can implement it.
Insert the following code under the <style> tag in the head section of your HTML document:
.box { width: 20px;
height: 50px;
transition: all 5.5s ease-out 0s;
-webkit-transition: all 5.5s ease-out 0s;
background-color: red;
-o-transition: all 5.5s ease-out 0s;
-moz-transition: all 5.5s ease-out 0s;
}
.box-animate {
width:900px
}
It should look like the following in your browser:
Now that our element is ready, we can proceed with the animation.
We will create a new section in the head called <script>, which allow us to add our JavaScript function.
<script>
init() {
var d = document.getElementsByClassName('box')[0];
d.className = d.className + " box-animate";
</script>
Next, we will add a trigger for the box animation so that when the page loads, the animation will take effect.
It should be like this:
Modify the body tag so it can automatically load the Javascript animation function once the page loads. Use the following:
<body onload="init()" >
Your final code should appear like this:
When you open a browser, you get the following output.
Discussion about this post