0

I want some transformations which are all targeting the same property to stack on top of each other.

Given my example below: If the button is clicked multiple times, the effects should add up. The box should then also move faster to the right according to the frequency of the clicks.

const clickHandler = () => {box.classList.add("move-box");}
.box{
width: 50px;
padding: 10px;
margin-top: 50px;
border: 1px solid black;
}

.move-box {
margin-left: 100px;
transition: margin-left 0.5s linear;
}
<button onclick="clickHandler()">Go over there</button>
<div id="box" class="box">Alright</div>
Tobi
  • 363
  • 5
  • 15

2 Answers2

0

Maybe you can pass a parameter in your function for the speed and use it in your css instead of using a static value or maybe increment it with every click.

EhtU
  • 41
  • 4
  • how could I pass a value to my css stylesheet? That has been an issue as well. I could use inline styles but it think it could be stacked then – Tobi Aug 21 '20 at 14:08
  • you can use css variables for that . please refer https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties – EhtU Aug 21 '20 at 14:11
0

You can set css value dynamically by javascript

(note: you should put transition: margin-left 0.5s linear; in .box)

const clickHandler = () => {
  const left = +box.dataset.left
  box.style.marginLeft = left + "px";
  box.dataset.left = left + 100;
}
.box {
  width: 50px;
  padding: 10px;
  margin-top: 50px;
  border: 1px solid black;
  transition: margin-left 0.5s linear;
}
<button onclick="clickHandler()">Go over there</button>
<div id="box" class="box" data-left=100>Alright</div>
apple apple
  • 10,292
  • 2
  • 16
  • 36
  • Amazing. Definitely learned something new. Ill try it out – Tobi Aug 21 '20 at 14:20
  • thats not a solutions which is also working for frameworks, is it? I am working with react and I was hoping that the general solution to the problem might also apply – Tobi Aug 21 '20 at 14:33
  • 1
    @Tobi This is pure js which should always work, if any framework break it, it's their problem to fix it (I believe react allow you to set attribute like [this random search result](https://stackoverflow.com/questions/26882177/react-js-inline-style-best-practices) ). – apple apple Aug 21 '20 at 14:59
  • @Tobi note that react is doing more or less what I'm showing, thus it would conflict with my code (and many native methods). – apple apple Aug 21 '20 at 15:01
  • I got it working simply using `style = { ... }` as well as moving the transition to the general class – Tobi Aug 21 '20 at 15:03