Marwane Bettach Marwane Bettach - 1 month ago 7
CSS Question

Change an elements height dynamically with jQuery

I need a div to get the height of another element if the class

collapsed
isn't in that element (I'm using bootstrap toggle collapse).

It works when the page is loaded but when I click on the element and the class
collapsed
is removed the
#careheight
doesn't change height.



$(document).ready(function() {
var divHeight = $("#care_and_washing").height();
if (!$("#care_and_washing").hasClass("collapsed")) {
$('#careheight').height(divHeight);
} else {
$('#careheight').height("10px");
}
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="care_and_washing" data-toggle="collapse" data-target="#demo" class="collapsed" style="font-family: 'NiveauGroteskMedium'; font-size: 11px; color: black;">Care & Washing</p>

<div style="cursor: default; padding-left: 13px;" id="demo" class="collapse">
<p style="font-family: Questrial, sans-serif; font-size: 10px;">• Dry Flat</p>
<p style="font-family: Questrial, sans-serif; font-size: 10px;">• Do Not Bleach</p>
<p style="font-family: Questrial, sans-serif; font-size: 10px;">• Tumble Dry Low</p>
<p style="font-family: Questrial, sans-serif; font-size: 10px;">• Iron Low</p>
<p style="font-family: Questrial, sans-serif; font-size: 10px;">• Hand Wash</p>
</div>

<div id="careheight"></div>




Answer

This happens because the function is only called on the document load. You'll have to assign it to a click as well:

$(document).ready(function(){
    changeHeight();
})

$('.element-you-want-to-click').click(function() {
    changeHeight()
});

function changeHeight() {
    var divHeight = $("#care_and_washing").height();

    if (!$("#care_and_washing").hasClass("collapsed")) {
        $('#careheight').height(divHeight);
    }

    else {
        $('#careheight').height("10px");
    }
}

This should work, if your initial function worked.