Home > Back-end >  Image not moving onclick
Image not moving onclick

Time:06-29

I'm trying make this image move 16px every click, but it's not moving. I've tried this:

But that only moves it once. So I tried something different that I found online.

Here is my code:

Html:

document.getElementById('player').style.left  = "-16px";

function left() {
   var left = parseInt(player.style.left);
   player.style.left = (left  16)   "px";
}
<img id="player" src="characters/prisoner-down.png"></img>
<img id="leftbtn" src="icons/left.png" onclick="left();"></img>

Edit: if it's useful to know, there are gonna be three more buttons for the other directions and the image I want to move is in another DIV from the image that moves it. On my editor it says that the symbol ` is invalid, so I'd like to avoid it.

CodePudding user response:

You can create a function that get the direction of the translation and the number of pixels to increment, then return a function that set style.transform of the element clicked, using a closure you can update the amount of pixels to translate, try this:

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

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

const translateRight = transform('right', 16);
const translateLeft = transform('left', 16);
<img onclick="translateRight(event);" src="https://images.rappi.com.ar/products/2311265-1622567743906.png?d=200x200&e=webp"></img>

<img onclick="translateLeft(event);" src="https://cdn.domestika.org/c_fill,dpr_auto,f_auto,h_256,pg_1,t_base_params,w_256/v1499705651/avatars/000/536/178/536178-original.jpg?1499705651" style="right: 0; position:absolute"></img>

CodePudding user response:

Give position property to the img which you want to move.

Like position: relative;, position: absolute; etc.

By positioning them you can use top, left, right and top properties.

don't use position: static; on that img cause above property has no effect on static element.

document.getElementById('player').style.left = "-16px";

function left() {
   let left = parseInt(player.style.left);
   player.style.left = `${parseInt(left 16)}px`;
}
img{
  /*important for using left, right, top and bottom properties*/
  position: relative;
}
<img id="player" src="https://i.postimg.cc/44pXvSwD/pngwing-com.png"></img>
<img id="leftbtn" src="https://i.postimg.cc/FRkMDYvr/Pngtree-right-arrow-flat-multi-color-3777297.png" onclick="left();"></img>

  • Related