Languages
[Edit]
EN

JavaScript - animate position changing

1 points
Created by:
Root-ssh
94100

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:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>
    
    body {
    	height: 200px;
    }

    .element {
        position: absolute;
        background: silver;
        transition: 0.3s;
    }

    .position-1 {
        top: 40px; left: 0;
        width: 100px; height: 100px;
    }

    .position-2 {
        top: 150px; left: 200px;
        width: 50px; height: 50px;
    }

  </style>
</head>
<body>
  <div id="element" class="element position-1">Some text here...</div>
  <button onclick="gotoPosition1()">Goto position-1</button>
  <button onclick="gotoPosition2()">Goto position-2</button>
  <script>
    
    var element = document.querySelector('#element');

    function gotoPosition1() {
        element.classList.remove('position-2');
        element.classList.add('position-1');
    }
    
    function gotoPosition2() {
        element.classList.remove('position-1');
        element.classList.add('position-2');
    }
    
  </script>
</body>
</html>

 

Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join