Reputation: 16513
Is it possible to know that if a DIV's width is set in Percentage or Pixel.
if (widthSetAsPixel) {
// code for doing something with respect to Pixel
}
if (widthSetAsPercentage) {
// code for doing something with respect to Percentage
}
Upvotes: 1
Views: 782
Reputation: 8065
You actually don't want to use jQuery as it will only give you the width in px even if it's set in percent (or some other unit). SO, in order to get the unit of the width you'll want to use window.getComputedStyle
. The problem still is that this only gives you the width in px unless the element has display: none;
SO... to get the width in its actual unit use this function I wrote:
function getStyle(el){
var display = window.getComputedStyle(el).getPropertyValue("display");
el.style.display = "none";
var width = window.getComputedStyle(el).getPropertyValue("width");
el.style.display = display;
return width;
}
Then to check whether or not the width is a percent do this:
var element = document.getElementById("myElementID");
var widthIsPercent = getStyle(element).indexOf("%") > -1;
This principle is true for other CSS properties as well like height
, left
, etc.
jsFiddle of it in action: http://jsfiddle.net/dwjqfLsz/
Upvotes: 4
Reputation: 42460
If the width has been set with CSS, you should be able to figure it out like this:
var width = $('#yourDiv').css('width');
var widthSetAsPercentage = width.indexOf('%') > -1;
var widthSetAsPixel = !widthSetAsPercentage;
Upvotes: 3