Home > Software engineering >  Setting div class width to the widest div is not updating
Setting div class width to the widest div is not updating

Time:10-18

I have a list of elements that content is generated with php from a database (I can multiply their values). I want them to have the width of the widest element - it should be updated on page load and click on select tag (multiplying the values). The script works on page load, but it's not updating the width when I'm clicking the select tag. Also, when the widest element shrinks, the width is not shrinking as it should, but staying the same as before.

<head>
  <script src="script.js" defer></script>
</head>

<select >
    <option value="0.5">0.5x</option>
    <option value="1" selected>1x</option>
    <option value="5">5x</option>
    <option value="10">10x</option>
</select>

// it looks like this - data-val generated from php <p class='ing_wght' data-val='$ing_weight'></p>
<p class='ing_wght' data-val='33'></p>
<p class='ing_wght' data-val='54'></p>
<p class='ing_wght' data-val='7312'></p>
<p class='ing_wght' data-val='6'></p>
// js/jquery code for multiplying is in the same file (above this one) as the script to change the width

$(".multiply_ing").on("click", function(){
    ingWidth();
});
$(window).on("load", function(){
    ingWidth();
});

function ingWidth(){
    let maxWidth = 0;
    let widestIngWght = null;
    let ingWght;
    
    $(".ing_wght").each(function(){
       ingWght = $(this);
       if(ingWght.width() > maxWidth){
            maxWidth = ingWght.width();
            widestIngWght = ingWght; 
       }
    });

    $(".ing_wght").css("width", maxWidth);
    console.log(maxWidth);
}

How can I fix these problems?

CodePudding user response:

Change:

$(".multiply_ing").on("click", function(){
    ingWidth();
});

To:

$(document).on("change", ".multiply_ing", function(){
    ingWidth();
});

This should work.

CodePudding user response:

So I found the solution. I had to add an if statement that removes the width from the class $(this) if it's wider or equal to previously defined max width.

$(".multiply_ing").on("click", function(){
    ingWidth();
});

$(window).on("load", function(){
    ingWidth();
});

function ingWidth(){
    let maxWidth = 0;
    let widestIngWght = null;
    let ingWght;
    
    $(".ing_wght").each(function(){
        
        ingWght = $(this);
        
        if(ingWght.width() >= maxWidth){
            ingWght.width("");
        }

        if(ingWght.width() > maxWidth){
            maxWidth = ingWght.width();
            widestIngWght = ingWght; 
        }
    });

    $(".ing_wght").css("width", maxWidth);
}

Maybe it will help someone in the future.

  • Related