I think that should work, but if for some reason it keeps on giving you the % width, What you can do is get the width and then divide it by the window width
var widthInPx = $(widnow).width()/$('yourElement').width
.width()
gets "...the current computed width" of the element that is used on, per the jQuery width documentation: http://api.jquery.com/width/, so the return value from $('#heatMapBar').width()
is in pixels, not percent. I would suggest using developers tool to check the width, it may be that in #heatMapBar
's current context, its width is 100px.
If you look here: http://jsfiddle.net/NkQXa/1/ you will see that #test
is set to width:50%;
, but it alerts the actual pixel width.
There can be a problem with multiple divs having percentage width:
<div style="width: 50%">
<div id="getMyWidth" style="width: 100%"></div>
</div>
In this case it returns 100 as width for the inner div for me. I solved it by taking the width of the outer div.
Based on Honzik's answer there this is a small workaround in case the element needed to specify it's width is inside a hidden parent element.
function getWidth(elemID) {
// get parent element unique id (must have)
var parentId = $("#"+elemID).parent().prop("id");
// remove the child element based on the specified element id
$("#"+elemID).remove();
// append a new child element but on body where most probably is not set to "display:none"
$("body").append('<div id="'+elemID+'">Hello</div>');
// get the width of the newly appended child element and store it to a variable
var width = $("#test2").width();
// remove child element from body
$("#"+elemID).remove();
// re-append child element to its former position under former parent element (having CSS attribute "display:none")
$(parentId).append('<div id="'+elemID+'">Hello</div>');
// display stored element width
alert(width);
}
// usage to get the element's width
getWidth("test2");
Try it in the below snippet!
function getWidth(elemID) {
var parentId = $("#"+elemID).parent().prop("id"); // your parent element should have a unique id specified
$("#"+elemID).remove();
$("body").append('<div id="'+elemID+'">Hello</div>');
var width = $("#test2").width();
$("#"+elemID).remove();
$(parentId).append('<div id="'+elemID+'">Hello</div>');
alert(width);
}
getWidth("test2");
.test {
border: 1px solid;
cursor: pointer;
height: 10px;
position: relative;
width: 100%;
display:none;
}
#test2{
width:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test1" class="test">
<div id="test2">
Hello
</div>
</div>
Another solution without jquery is to use the property clientWidth
available on HTMLElements
document.getElementById('test1').clientWidth