0

Ok, I want to have a CSS value such as the value of width: 50%; to be a variable defined in pixels. Let's say that the 50% width is perhaps 1000px, or 500px. I want the javascript to detect the pixel value of the percent.

I have tried several times with absolutely no luck.

3
  • 1
    not very clear. do you want to detect a width of an element and then work of 50% of that? Commented Jan 12, 2016 at 8:25
  • No, what I want to do is have a percentage translated into pixel value with javascript. Commented Jan 12, 2016 at 8:27
  • The @Azim's answer will put you right. Commented Jan 12, 2016 at 8:28

3 Answers 3

5

You can do it like below using jquery.

var width = $('#your_id').width();

Example

var width = $('#myDiv').width();
alert(width + 'px');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width: 200px;">
    <div id="myDiv" style="width: 50%;"></div>
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

Yes this would work fine, I will check mark it as soon as 7 mins are up(I have to wait 7 mins) BTW can you put width: 50% and do the same thing?
oh sorry I was looking at the first div. Thank you Azim!!
0
var total_width = $( window ).width();
var display_width = 50; //50%
var my_width_px = ((display_width * total_width) / 100); // 100 = 100%

This will may be helpful for you.

Comments

0

You can get the width in pixels using jQuery

var width = $('#mydivid').width();

Set the width of a div using jQuery

$("#mydivid").css("width", your_new_width);

Get width using javascript

document.getElementById("mydivid").offsetWidth; 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.