Get jQuery to set the width as a percentage, not pixels

I have an example here in jsFiddle , jQuery currently sets the width as a fixed pixel width. Therefore, when the width of the browser decreases, the bars leave the screen to the right. My question is, how can I get jQuery to set width instead of percentage?

<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); }); 
+6
source share
3 answers

You must first calculate the relative percentage between these two widths, for example:

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

Then you can set this as the target width without forgetting to add the number % (or it will get the value in px ), for example:

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

Working demo

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

Fiddle

+4
source

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 width of the CSS set up to 0% ;

By resizing the window, your SPAN will maintain the width % .

+1
source

All Articles