Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript percentage calculation for bar width

I am in need to calculate percentage of current values to attach it to the bars width:

<div class="bar"><span class="bar-inside" data-value="120"></span></div>
<div class="bar"><span class="bar-inside" data-value="1320"></span></div>
<div class="bar"><span class="bar-inside" data-value="670"></span></div>

I need to find maximum value (in this case it will be 1320) which will be 100% and depending on that calculate other bars width in percentage.

Thank you!

like image 556
ignaty Avatar asked Aug 09 '26 10:08

ignaty


1 Answers

var max = 0;
$('.bar').each(function() {
    max = Math.max(max, $('.bar-inside', this).data('value'));
})
.css('width', function() {
    return ($('.bar-inside', this).data('value') * 100 / max) + '%';
});

http://jsfiddle.net/8nmhY/

like image 89
dfsq Avatar answered Aug 11 '26 23:08

dfsq