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);
});
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);
});
Share
Improve this question
edited Mar 10, 2013 at 0:42
Sunyatasattva
5,8603 gold badges28 silver badges40 bronze badges
asked Mar 4, 2013 at 23:29
Hugo DBHugo DB
901 silver badge6 bronze badges
3 Answers
Reset to default 4$(".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
This is all you need:
LIVE DEMO
$(".meter > span").each(function() {
$(this).animate({ width: $(this).data("width")+"%" }, 3600);
});
this HTML:
<span data-width="88"></span>
and in the CSS set width to 0%
;
Resizing the window your SPAN
s will keep the %
width.