Herm Luna Herm Luna - 1 month ago 11
Javascript Question

Non-jQuery: Getting height even if the max-height is zero

This code is working fine.

What I am doing here is exaggerating the max-height of class active but what I need is to specify the exact height to be able to run the effect at the same speed.

For this example. I don't write a dynamic navbar and this is lack of condition but I think it covers what I want to specify.

If you click the w33racle, you'll see in console that there's a number. However, 0 is not the value I needed. I want it to be the height of ul.dropdown.active regardless of whether or not it has the .active class



let test_clicker = document.getElementById('testClicker');

test_clicker.onclick = (e) => {
let self = e.target || e.srcElement,
s_s = self.nextElementSibling.classList;

s_s.contains('active') ? s_s.remove('active') : s_s.add('active');

console.log(self.nextElementSibling.clientHeight);
}

.dropdown {
max-height: 0;
overflow: hidden;
transition: all 0.3s ease-in-out; }

.dropdown.active {
max-height: 500px; }

<ul>
<li>
<a id="testClicker">w33racle</a>
<ul class="dropdown">
<li><a>This</a><li>
<li><a>is</a><li>
<li><a>for</a><li>
<li><a>sample</a><li>
<li><a>only</a><li>
</ul>
</li>
</ul>





Any help would be appreciated. Thanks

Answer

You can easily get it by the adding the height of the children.

Take advantage of what javascript gave you. You don't need animationend in this case.

let test_clicker = document.getElementById('testClicker'),
    thisIsTheHeight = 0;

test_clicker.onclick = (e) => {
  thisIsTheHeight = 0;
  let self = e.target || e.srcElement,
      s_s = self.nextElementSibling.classList;
  
  s_s.contains('active') ? s_s.remove('active') : s_s.add('active');
  
  [].forEach.call(self.nextElementSibling.children, (elem) => {
    thisIsTheHeight += elem.clientHeight;
  });
  
  console.log(thisIsTheHeight);
}
.dropdown {
  max-height: 0;
  overflow: hidden;
  transition: all 0.3s ease-in-out; }

.dropdown.active {
  max-height: 500px; }
<ul>
  <li>
    <a id="testClicker">w33racle</a>
    <ul class="dropdown">
      <li><a>This</a><li>
      <li><a>is</a><li>
      <li><a>for</a><li>
      <li><a>sample</a><li>
      <li><a>only</a><li>
    </ul>
  </li>
</ul>