James Mitchell James Mitchell - 3 years ago 73
CSS Question

Unable to retrieve Height from a toggleClass jQuery

I want to get the height of a class that is toggled. When a button is clicked, the class

.category-menu-visible
is added. If the class exists, then I want to get it's height. But when I alert
menuHeight
, it is 0.

Small scale JSFiddle example

Actual Code:

jQuery

jQuery('.topics-btn').click(function(){
jQuery('.category-menu-wrap').toggleClass('category-menu-visible');

if (jQuery('.category-menu-wrap').hasClass('category-menu-visible')){
var menuHeight = jQuery('.category-menu-visible').height();
alert(menuHeight);
jQuery('.sidebar .content-wrap').css('margin-top', menuHeight);
} else {
jQuery('.sidebar .content-wrap').css('margin-top', 0);
}

});


CSS:

.category-menu-wrap {
width:100%;
height:0px;
background-color:#F7D5B6;
overflow: hidden;
transition: height .5s cubic-bezier(.27,1.76,.95,1.19);
}
.category-menu-visible {
height: 70px;
transition: height .3s cubic-bezier(.27,1.76,.95,1.1);
}


Why can't it retrieve the height?

Answer Source

You need to wait till transition finishes. Update: There is a useful event transitionend to do it:

jQuery('.topics-btn').click(function(){
  var $menu = jQuery('.category-menu-wrap');
  $menu.toggleClass('category-menu-visible');
  $menu.on("transitionend", function(){
    if (jQuery('.category-menu-wrap').hasClass('category-menu-visible')){
      var menuHeight = jQuery('.category-menu-visible').height();
      alert(menuHeight);
      jQuery('.sidebar .content-wrap').css('margin-top', menuHeight);
    } else {
      jQuery('.sidebar .content-wrap').css('margin-top', 0);
    }
  });

});
.category-menu-wrap {
  height: 0;
}
.category-menu-visible {
  height: 70px;
  transition: height .3s cubic-bezier(.27,1.76,.95,1.1);
}
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<button class='topics-btn'>Click</button>
<div class='category-menu-wrap'></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download