Fabio Brizzi
Fabio Brizzi

Reputation: 55

How to change img position with button click

Hi I'm trying to change position by 10px of my img when I click Suivant it moves by 10px to the right but when I click Precedent it doesn't go back by 10px can't seem to find the problem!

window.addEventListener("load", function(){
    btnPrec = document.getElementById('prec');
    btnSuiv = document.getElementById('suiv');

    var oImg = document.getElementById("img1");
    oImg.style.position="relative";
    oImg.style.left="0px";
    oImg.style.top="0px";

    btnSuiv.addEventListener("click", function(){
      oImg.style.left="10px";
    })

    btnPrec.addEventListener("click", function(){
      oImg.style.right="10px";
    })

}, false)

Upvotes: 2

Views: 60

Answers (1)

Mamun
Mamun

Reputation: 68933

You can use the left property by increasing/decreasing the unit:

window.addEventListener("load", function(){
  btnPrec = document.getElementById('prec');
  btnSuiv = document.getElementById('suiv');

  var oImg = document.getElementById("img1");
  oImg.style.position="relative";
  oImg.style.left="0px";
  oImg.style.top="0px";

  btnSuiv.addEventListener("click", function(){
    oImg.style.left = parseInt(oImg.style.left) + 10 + "px";
  })

  btnPrec.addEventListener("click", function(){
    oImg.style.left = parseInt(oImg.style.left) - 10 + "px";
  })

}, false)
<img src="/" id="img1">
<br>
<button type="button" id="prec">prec</button>
<button type="button" id="suiv">suiv</button>

Upvotes: 1

Related Questions