Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get jQuery to set width as percentage rather than pixels

I have an example set up here on jsFiddle, the jQuery currently sets the width as a fixed pixel width. So when the browser width is decreased the bars go off the screen to the right. My question is how do i get jQuery to set the width to a percentage instead?

<div class="bars">
    <div class="meter">
        <span style="width: 88%"></span>
    </div>
    <div class="meter">
        <span style="width: 62%"></span>
    </div>
</div>

$(".meter > span").each(function() {
    $(this)
        .data("origWidth", $(this).width())
        .width(0)
        .animate({
            width: $(this).data("origWidth")
        }, 3600);
});
like image 758
Hugo DB Avatar asked Mar 04 '13 23:03

Hugo DB


2 Answers

$(".meter > span").each(function() {
   $(this).data("origWidth", ($(this).width() / $(this).parent().width()) * 100)
          .width(0)
          .animate({ width: $(this).data("origWidth") + "%" }, 3600);
});

FIDDLE

like image 170
adeneo Avatar answered Oct 17 '22 20:10

adeneo


You have to first calculate the relative percentage between this two widths, like so:

var relativePercentage = ($(this).width()/$(this).parent('div').width())*100;

Then you can set this as the target width, remembering to add the % number (or it will get the value in px), like so:

$(this)
    .data("origWidth", $(this).width())
    .width(0)
    .animate({
        width: relativePercentage + '%'
    }, 3600);

Working demo

like image 37
Sunyatasattva Avatar answered Oct 17 '22 22:10

Sunyatasattva