Home > Mobile >  How to move element with position on every click Javascript
How to move element with position on every click Javascript

Time:09-29

So I have a button

        <button >Button</button>

And I want it to move 100px left everytime I click on it So I did this

item = document.querySelector(".item")
let moveItem =()=>{
   item.style.position = 'absolute'
   item.style.left  = '100px'
}

item.addEventListener("click", moveItem)
But it only moves one time. How do i move it everytime i click on it?

CodePudding user response:

First your brackets are wrong on your moveItem function so change these to curly braces, then style.left returns null or a string so you need to parse it as an int:

const item = document.querySelector(".item")
let moveItem = () => {                       // change bracket type
   item.style.position = 'absolute';
   
   const left =  item.style.left || 0;       // get left if it exists or default to zero
   
   item.style.left = `${parseInt(left, 10)   100}px`;   // change the left value to an int and add 100 
}

item.addEventListener("click", moveItem)
<button >Button</button>

CodePudding user response:

Logical error in generating the position left value

Adding position left like item.style.left = '100px' will keeps on generating a string consisting of 100px multiple times. First time it runs, it will gives you a result 100px which you sets for the position left, next time this operation will give you a result 100px100px which is an invalid value for position left. So it will not update the position left property with the new value, instead it keeps the old value.

My solution: Each time you click the button, get the current numeric value for the position left and 100 to that value.

item = document.querySelector(".item")
let moveItem =()=>{
   item.style.position = 'absolute'
   const currentpos = item.style.left.match(/\d /g);
   item.style.left = currentpos ?  currentpos[0]   100   'px' : '100px'
}
item.addEventListener("click", moveItem)
<button >Button</button>

  • Related