EN
JavaScript - animate position changing
1 points
In this short article we would like to show how to animate position changing using CSS contorlled by JavaScript logic.
Animation is posible by removing and adding class names with: element.classList.remove('class-name')
and element.classList.add('class-name')
and transition
style property.
Quick solution:
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
body {
7
height: 200px;
8
}
9
10
.element {
11
position: absolute;
12
background: silver;
13
transition: 0.3s;
14
}
15
16
.position-1 {
17
top: 40px; left: 0;
18
width: 100px; height: 100px;
19
}
20
21
.position-2 {
22
top: 150px; left: 200px;
23
width: 50px; height: 50px;
24
}
25
26
</style>
27
</head>
28
<body>
29
<div id="element" class="element position-1">Some text here...</div>
30
<button onclick="gotoPosition1()">Goto position-1</button>
31
<button onclick="gotoPosition2()">Goto position-2</button>
32
<script>
33
34
var element = document.querySelector('#element');
35
36
function gotoPosition1() {
37
element.classList.remove('position-2');
38
element.classList.add('position-1');
39
}
40
41
function gotoPosition2() {
42
element.classList.remove('position-1');
43
element.classList.add('position-2');
44
}
45
46
</script>
47
</body>
48
</html>