Amar Syla
Amar Syla

Reputation: 3663

Need to assign width to element by taking value from attribute

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

Answers (4)

Arun Raj
Arun Raj

Reputation: 969

$('.bar').each(function() {
var width = $(this).data("percent");
$(this).find('div').css("width",width+"%");
});

Upvotes: 1

Patrick Evans
Patrick Evans

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

Michael
Michael

Reputation: 16142

replace your jQuery code on:

$('.bar > div').css('width', function(){
    return $(this).parent().data('percent') + '%'
});

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388436

Try

$('.bar > div').css('width', function(){
    return $(this).parent().data('percent') + '%'
});

Demo: Fiddle

Upvotes: 5

Related Questions