Prev Demo
JavaScript
>
Requestanimationframe
Next Demo
Write code here
J
|
B
|
A
<!DOCTYPE html> <html> <head> <title>Demo</title> </head> <body> <h1>Moving colored portion on window</h1> <style> #myId { position: fixed; left: 10px; width: 100px; height: 50px; padding: 1em; background: lightgreen; color: #441515; font-size: medium; text-align: center; } </style> <p id="myId">Click here to move</p> <script> var a = document.getElementById('myId'), startTime = null, EndPosition = 2000, //* in pixels *// TimeSpeed = 1000; //* in milliseconds *// function myFunction(time) { if (time === undefined) { time = new Date().getTime(); //* getTime() returns only time part from the new Date() *// } if (startTime === null) { startTime = time; } a.style.left = ((time - startTime) / TimeSpeed * EndPosition % EndPosition) + 'px'; } a.onclick = function () { (function myAnimation() { myFunction(); requestAnimationFrame(myAnimation, a); })(); }; </script> </body> </html>
Note: We DO NOT save your trial code in our database.
Output