0

I am trying to trigger a transition by toggling a class. The class toggles and applies it's style to the element, but the transition does not trigger. The transition applies to all properties, so I don't think that that is the problem.

function expandFunction(element) {
  element.classList.toggle("setHeightStyle");
}
.setHeightStyle {
  height: 60px;
}

#expSect1 {
  overflow: hidden;
  cursor: pointer;
  transition: 1s;
}
<div class="setHeightStyle" id="expSect1" onclick="expandFunction(this)">
  <h1>Title</h1>
  <br>
  <p>Content!<br>More content!</p>
</div>

2 Answers2

1

Not only the comas in the HTML need to be fixed.

You need to specify the property on which the transition wil apply... If not sure, use all.

For the transition to take effect, the height has to be defined in the #expSect1 rule... Because the transition need a numeric value to start with. auto does not work.

Additionally, an id is more specific than a class... So you need to use both the class and the id on the rule to be toggled.

See the below working snippet.

function expandFunction(elementID) {
  let element = document.getElementById(elementID);
  element.classList.toggle("setHeightStyle");
}
#expSect1.setHeightStyle {
  height: 60px;
}

#expSect1 {
  overflow: hidden;
  cursor: pointer;
  height: 200px;
  transition: all 1s;
  background: blue;
}
<div class="setHeightStyle" id="expSect1" onclick="expandFunction(id)">
  <h1>Title</h1>
  <br>
  <p>Content!<br>More content!</p>
</div>
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
1

Your problem is that the height is not initially set on the element. I had to change the selector for the added class html because of your selector specificity with the id. In general, do not use IDs for styling. Only use them for javascript.

function expandFunction(element) {
  element.classList.toggle("setHeightStyle");
}
#expSect1 {
  height: 200px;
  overflow: hidden;
  cursor: pointer;
  transition: all 1s;
}

#expSect1.setHeightStyle {
  height: 60px;
}
<div class="setHeightStyle" id="expSect1" onclick="expandFunction(this)">
  <h1>Title</h1>
  <br>
  <p>Content!<br>More content!</p>
</div>
Pytth
  • 4,008
  • 24
  • 29