Thoppil
Thoppil

Reputation: 54

move image on each click Javascript

I want to move an image on each click but using this code works only on one click.

function moveright() {
  console.log("moveright invoked.");
  var myImg = document.getElementById("image");
  myImg.style.position = "absolute";
  var cLeft = myImg.style.left;
  if (cLeft == 500) {
    console("Maximum reached.");
  } else {
    myImg.style.left = (cLeft + 50) + "px";
  }
}
<img id="image" src="https://i.sstatic.net/TiYE3.jpg?s=32&g=1" onclick="moveright()" />

Upvotes: 0

Views: 79

Answers (2)

Laxmikant Dange
Laxmikant Dange

Reputation: 7688

Use parseInt, as style.left has value in px. If style.left is empty, pass 0 as initial value.

function moveright() {
  var myImg = document.getElementById("image");
  myImg.style.position = "absolute";
  var cLeft = parseInt(myImg.style.left || 0);

  if (cLeft == 500) {
    alert("Maximum reached.");
  } else {
    myImg.style.left = (cLeft + 50) + "px";
  }
}
<img id="image" src="https://i.sstatic.net/TiYE3.jpg?s=32&g=1" onclick="moveright()" />

Upvotes: 2

Nisarg Shah
Nisarg Shah

Reputation: 14541

  1. Give an initial left position value. You can add an inline style like this: style="left: 0px"

  2. Parse the left value to an integer before adding 50 px to it: var cLeft = parseInt(myImg.style.left);

function moveright() {
  var myImg = document.getElementById("image");
  myImg.style.position = "absolute";
  var cLeft = parseInt(myImg.style.left);
  
  if (cLeft == 500) {
    console("Maximum reached.");
  } else {
    myImg.style.left = (cLeft + 50) + "px";
  }  
}
<img id="image" src="https://i.sstatic.net/TiYE3.jpg?s=32&g=1" onclick="moveright()"  style="left: 0px" />

Alternatively, you can skip the left style declaration and get the computed style value using window.getComputedStyle.

function moveright() {
  var myImg = document.getElementById("image");
  myImg.style.position = "absolute";
  
  var cLeft = parseInt(window.getComputedStyle(myImg).left);
  
  if (cLeft == 500) {
    console("Maximum reached.");
  } else {
    myImg.style.left = (cLeft + 50) + "px";
  }  
}
<img id="image" src="https://i.sstatic.net/TiYE3.jpg?s=32&g=1" onclick="moveright()" />

Upvotes: 4

Related Questions