Зміст курсу
HTML & JavaScript Interactivity for Beginners
HTML & JavaScript Interactivity for Beginners
Animations with HTML and JavaScript
This chapter provides a basic overview of animating DOM elements in JavaScript. Once you gain knowledge of these fundamentals, you can implement complex animations using HTML and Javascript.
With JavaScript, you can move any DOM elements based on some pattern or formula. Following are the three primary Javascript functions that you can use in animations:
setInterval(myFunction, duration)
− calls themyFunction
after every millisecond as specified by duration;setTimeout( myFunction, duration)
− callsmyFunction
after duration milliseconds from now;clearTimeout(setTimeout_variable)
− clears any timer set by thesetTimeout()
functions.
Let's begin with a simple example of a manual animation in Javascript.
Manual Animation
You can move a DOM element on the screen with manual animation by setting its position property. We'll create a <div>
and animate it within its parent <div>
by setting its position top and left properties. Here’s the code:
index
index
index
The animation is relatively slow when you run this program, and you must click every time to move the element to the right. Thus, we can automate this process using the setTimeout()
function, which you'll discover below.
Automated Animation
This time we'll modify the example slightly differently, as the parent element will have a background color and a fixed width, height, and relative position.
The setTimeout
function will move the element to the left until the user clicks the stop button, which will call the stop
function and then clears the setTimeout
function. It'll also bring back the animating <div>
to its starting position.
Example with setTimeout Method
Here's the code:
index
index
index
Example with setInterval Method
In this program, the blue color <div>
will move every five milliseconds specified in the setInterval method by incrementing its left and top positions. Once it reaches the parent div's width and height, it returns to its original position.
index
index
index
Now you have a fair idea of how animation works. With this knowledge, you'll be able to write programs with advanced features.
Дякуємо за ваш відгук!