user3219369
user3219369

Reputation:

JavaScript "animation" not working as I expect

I've been trying to move a red box 20px on mouseover. But instead of adding 20px to the current position it just goes to position "20px".

I got the idea for this here: Move an image with the arrow keys using JavaScript

But it's not working for me :/

Thanks!

<html>
<head>
<meta charset="UTF-8">
<style>
#element {
position: absolute;
left:100px;
top:100px;
height: 140px;
width: 60px;
background-color: red;
}
</style>
</head>
<body>
    <div id="element"></div>
    <script>
    window.addEventListener('load', function () {
        boxElement = document.getElementById('element');
        if (boxElement) {
            boxElement.addEventListener('mouseover', function () {
                boxElement.style.left += 20 + 'px';
            });
        }
    });
</script>
</body>
</html>

Upvotes: 0

Views: 59

Answers (2)

CupawnTae
CupawnTae

Reputation: 14600

You're adding a string "20px" to an empty string, which is effectively setting the style property of the boxElement to "left: 20px", overriding the stylesheet.

You could get the current computed style of the element each time and add to it, or you could keep a closure-scoped variable with the position, like this:

window.addEventListener('load', function () {
    var x=window.getComputedStyle(boxElement,null).getPropertyValue("left");

    boxElement = document.getElementById('element');
    if (boxElement) {
        boxElement.addEventListener('mouseover', function () {
            x+=20;
            boxElement.style.left = x + 'px';
        });
    }
});

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 817128

boxElement.style.left returns a string which looks like "123px".

The first time you execute

boxElement.style.left += 20 + 'px';

it will be fine, since boxElement.style.left will be an empty string. But the second time, you are trying to set style.left to 20px20px (string concatenation!), so the browser simply ignores the new value, and keep the old one, 20px.

You have to parse the position out of the value first, using parseInt and then add to it:

var left = boxElement.style.left;
boxElement.style.left = (parseInt(left, 10) + 20) + 'px';

The other problem is that boxElement.style.left won't return the initial value which was inherited from the CSS class. For that you can use getComputedStyle and set it once before you bind the event handler:

var boxElement.style.left = 
    window.getComputedStyle(boxElement,null).getPropertyValue("left");

If you read the code of the linked question properly, you can see that that's exactly what was done there:

element.style.left = parseInt(element.style.left) - 5 + 'px';

Upvotes: 5

Related Questions