Move element position[click]

Hello,
Im trying to define a function that use the margin style of element for move element, for example:
when I click the button the element is move to 100px to the left.

here my code:

function boxmove() {
 element.style.marginLeft = "100px";
}

There is a no way to move element “click to click”, so don’t update the position…
Please, you can show me a method for move element in the new style position???

Thanks for the reguards.

Hello!
I have make add of my code, but there is an error because I can’t move my element step by step, look at this:

function moveRight(){
    box.style.position = 'relative';
    id = setInterval(animateFrame, 10);
    
    
    function animateFrame(){
      pos = pos + 10;   
      box.style.left = pos + 'px';    
      console.log(pos);
      if(pos == 200) {
        clearInterval(id);
      } 
    }
  }

Somebody can help me? when I click the button the element move of 200px only once and if I click another time the element is move over the screen…I would make an animation that update the regular position, If you understand me, please show me the right way.

Thank you.

I’m afraid I don’t really understand what you’re trying to achieve… do you want to make the element draggable with the mouse?

every time i click the button, my animated element you have to move of 200px. In my code the animated element is moved of 200px only once. There is solution? Thank you.

Well just set pos = 0 at the top of moveRight() then.

the complete code is here…but the element is moved only once… and if I click another time the element is moved infinite…there is a way for resolved this script??? Thank you.

var box = document.getElementById("box");
  var pos = 0;
  var id;
            
  function moveRight(){
    box.style.position = 'relative';
    id = setInterval(animateFrame, 10);
    
    
    function animateFrame(){
      pos = pos + 10;   
      box.style.left = pos + 'px';    
      console.log(pos);
      if(pos == 200) {
        clearInterval(id);
      } 
    }
    
  }

Ah okay. Well pos is never going to be 200 again, so a simple equality check won’t do the trick. You might use modulo instead:

if (pos % 200 === 0) {
  clearInterval(id)
}

thank you, now the code is ok…but you can explain this condition?..I’m Learning now javascript :smile:

It’s actually just mathematics. ;-) A modulo is the remainder of a division; so for example

201 mod 200 = 1
202 mod 200 = 2
.
.
.
399 mod 200 = 199
400 mod 200 = 0

And in JS (and many other programming languages), the sign for modulo is %.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.