Reputation: 3663
I have this HTML code:
<div class="skills">
<div class="skill">
<span>Photoshop</span>
<div class="bar" data-percent="80">
<div></div>
</div>
</div>
<div class="skill">
<span>Illustrator</span>
<div class="bar" data-percent="20">
<div></div>
</div>
</div>
<div class="skill">
<span>Wordpress</span>
<div class="bar" data-percent="30">
<div></div>
</div>
</div>
<div class="skill">
<span>Joomla</span>
<div class="bar" data-percent="65">
<div></div>
</div>
</div>
</div>
And this jQuery code:
var width = $('.bar').attr('data-percent');
$('.bar > div').css('width', width + "%");
Right now it's getting the first .bar's
value of the data-percent attribute, e.g. 40, and passing it as a CSS style, e.g. width: 40%
, but it's taking the first .bar's attribute only, and applying the same width to all the other elements. I want it to take the attribute for each of them, and assign their widths to each of them.
Upvotes: 1
Views: 684
Reputation: 969
$('.bar').each(function() {
var width = $(this).data("percent");
$(this).find('div').css("width",width+"%");
});
Upvotes: 1
Reputation: 42746
you can use the .each
function to handle each .bar
element, and you can use jquery's .data function to get data-* attributes instead of the .attr
function
$('.bar').each(function() {
var width = $(this).data("percent");
$(this).find('div').css("width",width+"%");
});
Upvotes: 2
Reputation: 16142
replace your jQuery code on:
$('.bar > div').css('width', function(){
return $(this).parent().data('percent') + '%'
});
Upvotes: 1
Reputation: 388436
Try
$('.bar > div').css('width', function(){
return $(this).parent().data('percent') + '%'
});
Demo: Fiddle
Upvotes: 5