DEV Community

Discussion on: JavaScript: My animation doesn't make the element start from the right position.

Collapse
 
edreeseg profile image
Ed Reeseg • Edited

Difficult for me to test because I'm away from home, but if you're looking to check what the CSS value is, you could use getComputedStyle.

element.style.right =
            // we get the value "450px" from getComputedStyle, 
            // and slice off the px to create a number.
            Number(getComputedStyle(element).right.slice(0, -2)) +
            (timePassed / 5) +
            "px";

Or, alternatively, instead of declaring the right attribute in your CSS, just declare it in your HTML inline if that'll be the result anyways.

<img width="300" height="300" style="right:450px"id="element" src="element.png" />

You can then just reference that value with element.style.right to do the same addition.

Smarter might be to use a keyframes animation that'd be exclusively in CSS. I'd check out this page: developer.mozilla.org/en-US/docs/W...

.element-slide {
    animation: 2s ease forwards slide-left;
}

@keyframes slide-left {
    from {
        right: 450px;
    }
    to {
        right: 900px;
    }
}

You can then toggle the element-slide class on the img element as needed.