Marwane
Marwane

Reputation: 189

jquery function works correctly only on first click

I have this function

$(".plusmenus1").on('click', function() {
    $('.plusmenus1 i').toggleClass("fa-plus fa-minus");
    $("#care_and_washing").toggleClass("collapsed_MB  ");
    changeHeight();
});
$(".plusmenus2").on('click', function() {
    $('.plusmenus2 i').toggleClass("fa-plus fa-minus");
});

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

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

    if (!$("#care_and_washing").hasClass("collapsed_MB")) {
        $('#careheight').css('height', divHeight + 'px');
    } else {
        $('#careheight').css('height', '10px');
    }
}

it works but it gets the var divHeight = $("#care_and_washing").height() + $("#demo").height();correctly only on the first click after that it gets the var without the + so it adds the height only of the #care_and_washing

HTML (I'll try to add only what's needed)

<div class="plusmenus1"><i data-toggle="collapse" data-target="#demo" style="float: left; position: relative; top: 3px; padding-right: 5px; color: black; font-size: 10px;" class="fa fa-plus collapsed" aria-hidden="true"></i>
<p id="care_and_washing" data-toggle="collapse" data-target="#demo" class="collapsed collapsed_MB" style="font-family: 'NiveauGroteskMedium'; font-size: 11px; color: black;">Care & Washing</p>
</div>
<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>

Upvotes: 0

Views: 77

Answers (1)

Mamdouh Saeed
Mamdouh Saeed

Reputation: 2324

Hidden_Element.height() and Hidden_Element.width() will be 0 so you need to show to get height and hide again like this

function changeHeight() {
  var care_h = $("#care_and_washing").height();
  var demo_h = $("#demo").height();

  demo_h = demo_h == 0 ? $("#demo").show().height() : demo_h;

  $("#demo").hide();

  var divHeight = care_h + demo_h;

  if (!$("#care_and_washing").hasClass("collapsed_MB")) {
    $('#careheight').css('height', divHeight + 'px');
  } else {
    $('#careheight').css('height', '10px');
  }
}

Upvotes: 2

Related Questions