Obtain average progress percentage of 3, 4 and 5 div's with jquery

0

First of all, thank you very much to all who read this question and want to help me. The title is confusing, but here I will try to capture it:

I have a container that sometimes has 3 div's, sometimes 4 div's or sometimes 5 div's, each container has a strip with css of a progress, I need to obtain the median of the advances of all the div's, if there's 3 , or 4 or 5.

The code is like this:

<div id="contenedor" class="container">
  <div class="row">
    <div class="avance col-md-4 progreso1">
      <div class="progresso">
        <div style="width: 65%"></div>
      </div>
    </div>
    <div class="avance col-md-4 progreso2">
      <div class="progresso">
        <div style="width: 20%"></div>
      </div>
    </div>
    <div class="avance col-md-4 progreso3">
      <div class="progresso">
        <div style="width: 4%"></div>
      </div>
    </div>        
  </div>
</div>

My intention is to obtain a bar with the total progress

in this case it would be something like this:

<div id="progreso-total" style="with: 29.66667%"></div>

I hope you can help me with this ...

PD, then you have to add all the percentages (%) and divide them by the number of div's that there is with "advance" class.

Thank you.

    
asked by Juan Ayala 23.12.2017 в 02:55
source

1 answer

0

progreso is defined as 0, then each of the divs .avance is traversed and the percentages are added. The key is to use .prop('style') , because if you directly access the width with .css('width') it returns the value in px .

If this you need to do it every time that one of the .avance changes, you will have to put it inside a function.

var progreso = 0;

$('.avance').each(function () {
    progreso += parseFloat($('.progresso div', this).prop('style')['width']);
});

if (progreso) {
    progreso = (progreso / $('.avance').length) + '%';
}

$('#progreso-total').css('width', progreso);

I'll give you a JSFiddle to try it out. I added a .text(progreso) to see what percentage is applying.

    
answered by 23.12.2017 / 03:13
source