fortherest fortherest - 3 months ago 14
CSS Question

Why progress-bar doesn't work properly?

I have created a simple basic progress-bar it works if I add just one progress element in my HTML page but if I added another one, first works very well but second not as expected.

Here's my Codepen

HTML:

<div class="ani-progressbar">
<div class="fill-progress" kac-puan="8">
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
</div>
<div class="ani-progressbar">
<div class="fill-progress" kac-puan="10">
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>


CSS:

.ani-progressbar{
width:100%;
height:5px;
margin-bottom:10px;
}
.fill-progress span{
display:block;
width:5px;
height:5px;
border:1px solid #9ad204;
float:left;
margin-left:1px;
}


jQuery:

$(document).ready(function(){

var getVal = $(".ani-progressbar .fill-progress").attr("kac-puan");
$(".ani-progressbar .fill-progress span").slice(0,getVal).each(function(index,element){

$(this).css("background","#9ad204");
});

});

Answer

You have to change your jQuery function as:

$(document).ready(function() {
    $(".ani-progressbar .fill-progress").each(function() {
        var getVal = $(this).attr("kac-puan");
        var thisParent = $(this);
        thisParent.children('span').slice(0, getVal).each(function(index, element) {
            $(this).css("background", "#9ad204");
        });
    });

});
  • Your function will only get the attr of first encountered progress-bar instead of that you have to get attr of each progress-bar i.e. why it only works for first not for the other ones.

  • Secondly you can simply take current progress-bar into a variable thisParent and slice all the children span elements as per there kac-puan attr value.

Here I have updated your Codepen

Comments