I want to create a percentage bar with the help of jquery and css. I am not able to make it work, since jquery css({}) not working. here are my codes.
*'width' : width - not working for me
//vote percentage
$('.vote-percent').each(function() {
var percentValue = $(this).find('.percent-num').text();
$(this).find('.percent-bar').attr('data-percentage', percentValue);
var width = $(this).find('.percent-bar').attr('data-percentage');
$(this).find('.percent-bar').css({
'width': width
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<span >65%</span>
<div ></div>
</div>
<div >
<span >25%</span>
<div ></div>
</div>
<div >
<span >10%</span>
<div ></div>
</div>
CodePudding user response:
You did some extra steps which I removed from your code, then I added simple styling so you can see the bars.
$('.vote-percent').each(function(){
var percentValue = $(this).find('.percent-num').text();
$(this).find('.percent-bar').css('width', percentValue);
});
.percent-bar {
background-color: red;
height: 10px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<span >65%</span>
<div ></div>
</div>
<div >
<span >25%</span>
<div ></div>
</div>
<div >
<span >10%</span>
<div ></div>
</div>
CodePudding user response:
Don't read from HTML text, use the data
attribute and read from there.
//vote percentage
$('.vote-percent').each(function() {
var width = $(this).data('percentage');
$(this).find('.percent-num').text(width);
$(this).find('.percent-bar').css({ width });
});
.percent-bar {
background: #3c3f50;
height: 30px;
border-radius: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-percentage="65%">
<span ></span>
<div ></div>
</div>
<div data-percentage="25%">
<span ></span>
<div ></div>
</div>
<div data-percentage="10%">
<span ></span>
<div ></div>
</div>