Dynamically animate/transition CSS height based on each dropdown's container height

by lasha

HTML

<ul>
    <li>
        <a href="asdasd">NAVITEM THREE</a>
        <div class="nested-dropdown">1. Content of the dropdown goes here<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1</div>
    </li>
    <li>
        <a href="asdasd">NAVITEM THREE</a>
        <div class="nested-dropdown">2. Content of the dropdown goes here<br>1<br>1</div>
    </li>
    <li>
        <a href="asdasd">NAVITEM THREE</a>
        <div class="nested-dropdown">3. Content of the dropdown goes here<br>1<br>1<br>1<br>1<br>1<br>1</div>
    </li>
</ul>

CSS

body {
    margin: 0;
    padding: 0;
}

ul {
    margin: 0;
    padding: 0;
}

li {
    float: left;
    list-style: none;
    padding-right: 20px;
}

li:last-child {
    padding-right: 0;
}

.nested-dropdown {
    opacity: 0;
    -webkit-transition: height 0.2s ease-in-out, opacity 0.2s ease-in-out;
    /* height: 0; */
    /* padding-top: 20px; */
    /* border: 1px solid #000; */
    position: absolute;
    left: 0;
    width: 100%;
    background-color: #ccc;
    /* display: none; */
    overflow: hidden;
}

li:hover .nested-dropdown {
    /* display: block; */
    opacity: 1;
    z-index: 1;
}

JavaScript

var itemNames = [];

$(".nested-dropdown").each(function(i, el){
    itemNames.push("nav"+i);
    $(this).addClass(itemNames[i]);
    
    $('body').append('<style type="text/css">li .nested-dropdown.'+ itemNames[i] +' { height: 0; } li:hover div.nested-dropdown.'+ itemNames[i] +' { height: '+ $(this).height() +'px; }</style>');
    console.log($('body'));
});

for (var i = 0; i < itemNames.length; i++){
     $("."+itemNames[i]).css("background-color","<?php echo $color; ?>");
}