Ulises Colen
Ulises Colen

Reputation: 405

how to get the attribute value of 'width' property

This is my progress bar http://jsfiddle.net/vjNpj/2247/ , I want the span (percentage value) can change together when the width of the div changed. like when the width is 50%, the span will display 50%..

what I can think of is attr(), but how to get its value?

I tried this but not working

var percent = $('#progressbar > div').attr('width');
alert(percent);

Upvotes: 0

Views: 254

Answers (5)

DGS
DGS

Reputation: 6025

Here is a JSFIDDLE that achieves what you are after

$progress_bar = $('#progressbar');
var progressbar_width = Math.floor(100 * ($progress_bar.find('div').width()) / $progress_bar.width())
$progress_bar.find('span').text(progressbar_width + '%')

You will have to call this code everytime you update the width of the progress bar.

Upvotes: 0

Ishan Jain
Ishan Jain

Reputation: 8171

You need to do some mathematical calculation for this work -

var percent = $('#progressbar div').width();
var Percent_Load = parseInt((percent * 100)/ $('#progressbar').width(), 10)
alert(Percent_Load);

Try This

Upvotes: 0

Deepak Ingole
Deepak Ingole

Reputation: 15772

Lets understand this first

The difference between .css(width) and .width() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). The .width() method is recommended when an element's width needs to be used in a mathematical calculation.

So you can do,

alert($('#progressbar > div').css("width"));  // 388
alert($('#progressbar > div').prop("width")); // 388px;

Fiddle for more understanding

Upvotes: 3

Sachin Verma
Sachin Verma

Reputation: 3812

Hey width is an attribute just like value is an attribute, so you may only want to get width not value of width.And for that I recommend answer by amit aggarwal.

Upvotes: 0

Rituraj ratan
Rituraj ratan

Reputation: 10388

var percent = $('#progressbar > div').width();

or

var percent = $('#progressbar > div').css('width');


alert(percent);

demo

Upvotes: 0

Related Questions