CSS Transition on Class Change

Viewed 861

I am trying to transition width property when certain class is added or removed to element using JavaScript. Transition works fine if I try to change property on :hover, but it won't work if I try to transition it by adding or removing class. What am I doing wrong?

function activate(number) {
  var bottom1 = document.getElementById("bottom-1");
  var bottom2 = document.getElementById("bottom-2");
  if (number === 1) {
    bottom1.classList.add("active");
    bottom2.classList.remove("active");
  } else {
    bottom2.classList.add("active");
    bottom1.classList.remove("active");
  }
}
body {
  display: flex;
  }
.container {
  position: relative;
  }
 .bottom-1 {
    position: absolute;
    bottom: 0px;
    right: 0px;
    height: 2px;
    background-color: red;
    transition: width 1s ease;
    }

 .bottom-2 {
    position: absolute;
    bottom: 0px;
    left: 0px;
    height: 2px;
    background-color: red;
    transition: width 1s ease;
    }
.active {
  width: 100%;
    }
<div class="container">
    <button onclick="activate(1)">Button 1</button>
    <div id="bottom-1" class="bottom-1 transition"></div>
</div>
<div class="container">
   <button onclick="activate(2)">Button 2</button>
   <div id="bottom-2" class="bottom-2 transition"></div>
</div>

1 Answers

you need to define width in button CSS before transition it:

function activate(number) {
  var bottom1 = document.getElementById("bottom-1");
  var bottom2 = document.getElementById("bottom-2");
  if (number === 1) {
    bottom1.classList.add("active");
    bottom2.classList.remove("active");
  } else {
    bottom2.classList.add("active");
    bottom1.classList.remove("active");
  }
}
body {
  display: flex;
  }
.container {
  position: relative;
  }
 .bottom-1 {
    position: absolute;
    bottom: 0px;
    right: 0px;
    height: 2px;
    width: 0%;
    background-color: red;
    transition: width 1s ease;
    
    }

 .bottom-2 {
    position: absolute;
    bottom: 0px;
    left: 0px;
    height: 2px;
    width: 0%;
    background-color: red;
    transition: width 1s ease;
    }
.active {
  width: 100%;
    }
<div class="container">
    <button onclick="activate(1)">Button 1</button>
    <div id="bottom-1" class="bottom-1 transition"></div>
</div>
<div class="container">
   <button onclick="activate(2)">Button 2</button>
   <div id="bottom-2" class="bottom-2 transition"></div>
</div>

Related