5

In my code, I want to use the transition only when the width turns wider. When the width decrease I don't want any animation. can I do with CSS only? Add/remove classes is not an option for me.

function changeCss() {
  document.getElementById('squareId').style.width = "300px";
}

function reset() {
  document.getElementById('squareId').style.width = "100px";
}
.square {
  background-color: red;
  width: 100px;
  height: 100px;
  transition: width 1s linear;
}
<div id="squareId" class="square"></div>

<button onclick="changeCss()">increase</button>
<button onclick="reset()">decrease</button>

JSFiddle

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
SIE-Coder
  • 105
  • 1
  • 7
  • css action you can use `id:checked` select method follow this https://stackoverflow.com/questions/13630229/can-i-have-an-onclick-effect-in-css – Saravana Mar 07 '18 at 09:11

1 Answers1

6

Adjust the transition at the same time in the JS code:

window.changeCss = function() {
  document.getElementById('squareId').style.transition = "width 1s linear";
  document.getElementById('squareId').style.width = "300px";
}
window.reset = function() {
  document.getElementById('squareId').style.transition = "none";
  document.getElementById('squareId').style.width = "100px";
}
.square {
  background-color: red;
  width: 100px;
  height: 100px;
}
<div id="squareId" class="square">

</div>
<button onclick="changeCss()">increase</button>
<button onclick="reset()">decrease</button>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415