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);
});
$(".meter > span").each(function() {
$(this).data("origWidth", ($(this).width() / $(this).parent().width()) * 100)
.width(0)
.animate({ width: $(this).data("origWidth") + "%" }, 3600);
});
FIDDLE
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With