Smoothly Interpolating Changes Position Animation Often when you get user input e g position you d set an update timer to manually update the position of the object i e interpolate the position or other attribute in code However CSS has a number of really useful helper transition methods builtin e g linearly change ease in out The following example lets you click a target location to move the object to however the movement is smoothly transition managed by the style sheet Try changing the transition type e g ease to linear style body height 200px box position absolute left 20px top 20px transition all 2s ease border 1px solid blue width 30px height 30px style div id box div script document body onclick move function move event console log clicked let box document getElementById box box style left event clientX 10 px box style top event clientY 10 px console log event clientX console log ready script Note you can actually read in JavaScript the CSS transition value so you know what value it s at You have to use getComputedStyle to get the actively changing value can t just read it from the css style directly style box width 80px height 80px transition background color 10s pink background orange blue background blue style div id box class pink div p code getComputedStyle box backgroundColor code code span id computedstylevalue span code p button id turnblue Turn blue button button id turnorange Turn orange button script const box document getElementById box const turnBlueButton document getElementById turnblue const turnOrangeButton document getElementById turnorange const computedStyleValueSpan document getElementById computedstylevalue turnBlueButton onclick box classList add blue box classList remove orange turnOrangeButton onclick box classList add orange box classList remove blue const computedStyleObj getComputedStyle box computedStyleValueSpan textContent computedStyleObj backgroundColor setInterval computedStyleValueSpan textContent computedStyleObj backgroundColor 50 script
Style to get the actively changing value can t just read it from the css style directly style box width 80px height 80px transition background color 10s pink background orange blue background blue style div id box class pink div p code getComputedStyle box backgroundColor code code span id computedstylevalue span code p button id turnblue Turn blue button button id turnorange Turn orange button script const box document getElementById box const turnBlueButton document getElementById turnblue const turnOrangeButton document getElementById turnorange const computedStyleValueSpan document getElementById computedstylevalue turnBlueButton onclick box classList add blue box classList remove orange turnOrangeButton onclick box classList add orange box classList remove blue const computedStyleObj getComputedStyle box computedStyleValueSpan textContent computedStyleObj backgroundColor setInterval computedStyleValueSpan textContent computedStyleObj backgroundColor 50 script