Skip to content
Advertisement

Image jumping to last position translation movement

I have some buttons that move an image with translation, but when I press one button then another and then the first one again, it jumps to where I was the the last time I pressed the first button.

Here is the JavaScript responsible for moving the image.

function transform(side, n) {
    let translatePixels = 0;

    if (side == 'right') {
        return function(e) {
            translatePixels += n;
            player.style.transform = `translate(${translatePixels}px)`;
        }
    }
    if (side == 'left') {
        return function(e) {
            translatePixels -= n;
            player.style.transform = `translate(${translatePixels}px)`;
        }
    }  
                       if (side == 'top') {
        return function(e) {
            translatePixels -= n;
            player.style.transform = `translateY(${translatePixels}px)`;
        }
    }     
if (side == 'bottom') {
        return function(e) {
            translatePixels += n;
            player.style.transform = `translateY(${translatePixels}px)`;
        }
    }     
}

const translateRight = transform('right', 8);
const translateLeft = transform('left', 8);
const translateTop = transform('top', 8);
const translateBottom = transform('bottom', 8);

Advertisement

Answer

enter image description here

basically creating two objects inside a JSON variable. x and y we can solve this.

also, I use switch statement to reduce the code.

player.style.transform = `translate(${x}px, ${y}px)`;

the translate() in css have two parameters, the first for x, the second for y.
so we add at the end the style only one time!


move the variable translatePixels outside the function.
by doing this the -= and += we will work.

this bug happens because every time you click one button, the variable will be reset to 0.

if you put the variable outside, the only first time the user opens the website it will be 0, the other times it will work fine (with saved value)

let player = document.querySelector("#player");

let translatePixels = {
    x: 0,
    y: 0
};

let { x, y } = translatePixels;

function transform(side, n) {
    switch (side) {
        case "right":
            x += n;
            break;
        case "left":
            x -= n;
            break;
        case "bottom":
            y += n;
            break;
        case "top":
            y -= n;
            break;
    }

    player.style.transform = `translate(${x}px, ${y}px)`;
}
<div id="player">I am the player!</div>

    <div id="container">
        <button onclick="transform('top', 8)">top</button>
        <button onclick="transform('bottom', 8)">bottom</button>
        <button onclick="transform('left', 8)">left</button>
        <button onclick="transform('right', 8)">right</button>
    </div>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement