Search code examples
javascriptcsscss-transitionscss-transforms

CSS incrementing transition animation on every button click


Given

var box = document.querySelector('.box');

document.addEventListener("click", (event) => {
  if (!event.target.closest("button")) return;
  
  if(event.target.id === "button") {
    box.classList.add('move');
  } 
    
});
.box {
    width: 100px;
    height: 100px;
    background-color: #000;
    transition: transform 1s;
}

.move {
    transform: translateX(20px);
}
<div class="box"></div>
<button id="button">button</button>

with a JS Fiddle here.

I want the box's x-position to increment by 20px on every button click.


I am not sure how to proceed. I initially tried using @KeyForms but that requires the from and to prefixes, on which I cannot (I think) add a variable value. Same issue arises here, it seems I cannot have a variable in the css code which I can increment. Am I using the correct function at all (transition) ?

I also tried

if(event.target.id === "button") {
    if(!box.classList.contains('open')){
        box.classList.add('open');
    }else {
        box.classList.remove('open');
    }
  }

but that seems to move the box back and forth repetitively.

Does anyone have any tips or ideas? (I am adding the Javascript tag, since I suspect this problem may potentially be solved in JS directly).


Solution

  • You can store the x position in a variable, increment by 20 every click and apply it to the transform style property:

    var x = 0, box = document.querySelector('.box');
    button.addEventListener('click', function() {
      x += 20, box.style.transform = `translateX(${x}px)`;
    })
    .box {
      width: 100px;
      height: 100px;
      background-color: #000;
      transition: 1s;
    }
    <div class="box"></div>
    <button id="button">button</button>