Friday , 17 November 2017
Home / Programming / JavaScript / Animation – JavaScript Tutorial
Animation
Animation

Animation – JavaScript Tutorial

This tutorial is part of the JavaScript tutorial series for beginners. To view the whole list of tutorials available and the order in which you should follow them, then click here.

Animation is an exciting topic in JavaScript. There are many tools out there to perform animations from basic to advance. Some of these tools are actual programs that allow you to input some numbers and then it takes care of the programming part of it. In this mini tutorial series, we’re going to be creating animations with pure JavaScript.

Animating objects can be very difficult because you have to program every part. This includes timing, easing, transitions, start and finish points. Not only that, you have to write the equations to get your object to move where you want it to. I’ll go more in depth about this in a later tutorial. For now, we’ll learn how to get started with animating objects and the very basics of it.

Setting up our HTML Document

Let’s update the body tags in our HTML document to this.

All we’re doing is creating a div tag with the id foo. We will be animating this div tag by moving it from left to right. Very simple!

Now, we’re also going to do some CSS changes to this div element, so add this style tag inside your <head></head> tags.

We’re not really doing anything special here. These styles just make it easier to visualize our animation. By making our text bigger, changing the background color, and adding a border. There is 1 important style however.

We change the position to absolute. This allows us to take advantage of the left, right, top and bottom properties. If we had other elements on the page, which you will occasionally, then by setting it to absolute, you allow this object to move freely without hurting other elements.

Setting Up The Script

Clear your script and add this bit of code.

Alright, the first variable we created is called frames and is set to the value of 0. Let’s talk about what frames are in general. Forget about our script for a moment and let’s discuss what a frame is in the computer world. Whenever you see an animation, you’re really not seeing the object move in real time. What you’re seeing is something like a picture book.

Let’s say you had a book with a bunch of pictures. If you were to flip through every page quickly, you would see a little movie. This is what an animation is. It’s just a bunch of pictures or frames with different positions of the object. Each picture is what’s called a frame.  Soon, we’ll be changing the frame from 0 to a 100. You’ll see in a moment what I mean.

Next, we create a variable called foo which will contain our div element with the id foo. We decide to update it’s left position to 0px. Why do we do this? We didn’t we do it in our style tags in our HTML document? Well, to put it simply, JavaScript needs to know the position of the element.

As I stated earlier, JavaScript needs to know the starting point and ending point of each animation. So, if we didn’t add this line of code, then our animation wouldn’t work anyway.

Let’s create the function that will take care of the animation. Add this bit of code into your script.

Our function moveBox() will do what the name says, move the box. The first thing that will happen is increment the frame by 1. Next, is where we actually move our div element. We update it’s left property to the value of it’s current position plus 5 pixels.

So, how is this done? Well, first we grab the current value and parse it. The parseInt() function takes in a string and converts it into an integer. Even though JavaScript has dynamic datatypes, you should make sure the value is an integer or things would just get messed up. After that, we add 5. Next, we also add the string px. Why? Well, remember, we’re manipulating CSS and CSS needs to know the unit of measurement.

Adding A Timer

Inside your function, add this bit of code after you update the position of our element.

The setTimeout() function allows you to run a bit of code after a certain amount of time. There’s 2 parameters. The first parameter takes in the name of the function you want to run. You’ll notice we omit the () after it. You don’t need it. The second parameter takes in the time the code will execute.

You should take note that the time you put in is in milliseconds. 1000 milliseconds equals  1 second. So, 20 milliseconds from now, this function will run. We store this in a variable so we can refer to it later. You’ll see in a moment why we do this.

The if statement will check if the current frame is 100. Meaning, this function will run 100 times. If 100 frames has passed, then we clear out our timer. The clearTimeout() function will do that for us. You simply pass in the timer you created. In our case, it would be the timer variable.

So, how does this all play out? Well, we have to do one more thing and I’ll break it all down for you. After your function, add this bit of code.

What does this line do? Well, first we access the window object. The window object is your browser basically. The window object allows you to close, open and use events. In our case, we want to use the onload event. This event will run when everything in our browser is loaded. We want to make sure our div element and the styles are applied before we run anything. Then, we call the moveBox() function.

Breaking It Down

So, first we call the moveBox() function. From there we move the box 5 pixels to the left. Next, we create a timer that will execute our function again after 20 milliseconds. Before the function is over, we check if the current frame is 100.  If it isn’t, then our function is finished. Once 20 milliseconds has passed, then the function will execute and the timer expires. So, we have to create the timer each time the function runs. This function runs faster than our timer, so we can check if 100 frames has passed. If so, then we can end our timer thus ending our animation.

Efficiency

We’re done! Before I finish, I have to talk about efficiency. See, every time you perform an animation, it takes up some CPU.This is because you have a timer in place. Your browser also has to react to any element changes or adjustments. This is especially true when performing multiple animations at once.  I’m not saying to stay away from animations, but please take the time to code efficiently.

Alternatives

Animations can get difficult. It requires a lot of logic and a good understanding of math. Luckily, developers have created libraries that will help you with animating objects. Here are a few.

http://jquery.com/

http://www.greensock.com/

http://mootools.net/

All of these are great libraries and all of them come down to a matter of preference.

Conclusion

This concludes our animation project. Hopefully you got a basic understanding of animating objects. Animation is truly experimental so don’t be discouraged if you don’t get what you want the first time.

About Jasko Koyn

Check Also

Try-Catch Statement

Try-catch Statement – Advanced JavaScript Tutorial

The try-catch statement is a unique way to handle errors. When errors occur, usually it …

Leave a Reply

Your email address will not be published. Required fields are marked *

ULTIMATE WORDPRESS DEVELOPMENT COURSE
Want to learn how to create your own custom WordPress plugins and themes? Check out my course!
Get 93% off my course. You'll also learn how to integrate WooCommerce and BuddyPress into your projects. This is a limited time offer
Yes, I would like to get 93% off your course!
No Thanks!
close-link