recruit_man recruit_man - 1 month ago 10
CSS Question

How can I make dynamic progress bar using just jquery?

I wrote a code for progressbar using jquery it works as expect but if I add second element all element works same that is why I guess I have to make it dynamic but I have no idea to do how can I make it as dynamic ?

HTML

<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<div class="trustyou-progressbar pull-right">
<p class="trustyou-puan">100/72 Puan</p>
<div class="progressFill">
<span class="ani-puan" ani-puan="72"></span>
</div>
</div>


<div class="trustyou-progressbar pull-right">
<p class="trustyou-puan">100/39 Puan</p>
<div class="progressFill">
<span class="ani-puan" ani-puan="39"></span>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</body>
</html>


CSS

.trustyou-progressbar{
width:100px;
}
.trustyou-puan{
font-size: 13px;
color:#494949;
font-weight: 500;
}
.progressFill{
width:100%;
height:6px;
background:#222222;
}
.ani-puan{
display:block;
height:100%;
}


JQUERY

var getprogressPuan = $('.ani-puan').attr('ani-puan');
$(".ani-puan").css("width",getprogressPuan+"%");
if((getprogressPuan>0) && (getprogressPuan<=40)){
$(".ani-puan").css("background","#ca2424");
}else if((getprogressPuan>=40) && (getprogressPuan<75)){
$(".ani-puan").css("background","#d6d824");
}else if((getprogressPuan>=75)){
$(".ani-puan").css("background","#9ad204");
}


click to see demo

Answer

Use an iterator to apply your function to all elements:

$('.ani-puan').each(function() {

  var getprogressPuan = $(this).attr('ani-puan');
  $(this).css("width", getprogressPuan + "%");
  if ((getprogressPuan > 0) && (getprogressPuan <= 40)) {
    $(this).css("background", "#ca2424");
  } else if ((getprogressPuan >= 40) && (getprogressPuan < 75)) {
    $(this).css("background", "#d6d824");
  } else if ((getprogressPuan >= 75)) {
    $(this).css("background", "#9ad204");
  }

});

Here is the sample page