mrpinkman
mrpinkman

Reputation: 211

get css width of an element and convert it to percentage

i have this code:

HTML

<div class="bar-value"></div>

CSS

.bar-value{
    width: 50%;
    height: 28px;
    background: #8BBDE8;
}

JQUERY

$(document).ready(function(){
    var percent = $('.bar-value').css('width');
});

the problem is that this returns the width of the div in pixels (in this case: 200px). I want that to return the value of the div in percentage (50%).

Thanks in advance!

Upvotes: 1

Views: 2552

Answers (2)

blex
blex

Reputation: 25634

To get a percentage, you need the width of it's parent. Try this :

$(document).ready(function(){
    var element = $('.bar-value');
    var percent = element.css('width')/element.parent().width()*100+'%';
});

Upvotes: 3

Tofandel
Tofandel

Reputation: 3565

This question has already been answered here

You have to implement it yourself :

var width = $('.bar-value').css('width');
var parentWidth = $('.bar-value').offsetParent().css('width');
var percent = 100*width/parentWidth;

Upvotes: 1

Related Questions