Find the "Potential" Width of a Hidden Element

Find the potential width of a hidden element

The only thing I can think of is to show it (or a clone of it) to allow retrieval of the offsetWidth.

For this measurement step, just make its position absolute and its x or y value a big negative, so it will render but not be visible to the user.

Need to find height of hidden div on page (set to display:none)

You need to make element's parent visible for that one very short moment while you're getting element's dimensions. In a generic solution, all ancestors are usually traversed and are made visible. Then their display values are set back to original ones.

There are performance concerns of course.

We considered this approach in Prototype.js implementation but ended up with getWidth and getHeight making only actual element visible, without traversing ancestors.

The problem with alternative solutions - such as taking element out of "hidden" parent - is that certain styles might no longer apply to an element once it's out of its "regular" hierarchy. If you have a structure like this:

<div class="foo" style="display:none;">
<div class="bar">...</div>
</div>

and these rules:

.bar { width: 10em; }
.foo .bar { width: 15em; }

then taking element out of its parent will actually result in wrong dimensions.

How do you find the dimensions of a display: none element?

Use window.getComputedStyle()

var o = document.getElementById('output');var wmd1 = document.getElementById('whats-my-dims1');var wmd2 = document.getElementById('whats-my-dims2');o.innerHTML = 'wmd1: "' + window.getComputedStyle(wmd1).getPropertyValue("width") + '", "' + window.getComputedStyle(wmd1).getPropertyValue("height") + '", wmd2: "' + window.getComputedStyle(wmd2).getPropertyValue("width") + '", "' + window.getComputedStyle(wmd2).getPropertyValue("height") + '"';
#some-hidden-div{  display: none;}.whats-my-dims{  display:block;  width: 69px;  height: 42px;  background-color: #f00;}
<div id='output'>  Processing... :p</div><div>  Sooo... How do I get the width and height of whats-my-dims1?</div><div id='some-hidden-div'>  <div class='whats-my-dims' id='whats-my-dims1'></div></div><div class='whats-my-dims' id='whats-my-dims2'></div>

jQuery - Get Width of Element when Not Visible (Display: None)

Here is a trick I have used. It involves adding some CSS properties to make jQuery think the element is visible, but in fact it is still hidden.

var $table = $("#parent").children("table");
$table.css({ position: "absolute", visibility: "hidden", display: "block" });
var tableWidth = $table.outerWidth();
$table.css({ position: "", visibility: "", display: "" });

It is kind of a hack, but it seems to work fine for me.

UPDATE

I have since written a blog post that covers this topic. The method used above has the potential to be problematic since you are resetting the CSS properties to empty values. What if they had values previously? The updated solution uses the swap() method that was found in the jQuery source code.

Code from referenced blog post:

//Optional parameter includeMargin is used when calculating outer dimensions  
(function ($) {
$.fn.getHiddenDimensions = function (includeMargin) {
var $item = this,
props = { position: 'absolute', visibility: 'hidden', display: 'block' },
dim = { width: 0, height: 0, innerWidth: 0, innerHeight: 0, outerWidth: 0, outerHeight: 0 },
$hiddenParents = $item.parents().andSelf().not(':visible'),
includeMargin = (includeMargin == null) ? false : includeMargin;

var oldProps = [];
$hiddenParents.each(function () {
var old = {};

for (var name in props) {
old[name] = this.style[name];
this.style[name] = props[name];
}

oldProps.push(old);
});

dim.width = $item.width();
dim.outerWidth = $item.outerWidth(includeMargin);
dim.innerWidth = $item.innerWidth();
dim.height = $item.height();
dim.innerHeight = $item.innerHeight();
dim.outerHeight = $item.outerHeight(includeMargin);

$hiddenParents.each(function (i) {
var old = oldProps[i];
for (var name in props) {
this.style[name] = old[name];
}
});

return dim;
}
}(jQuery));

Get dimensions of element located in hidden parent

Okay, here is what I am thinking. In theory, it should work for any element whether hidden or a child of one or more hidden ancestors. See https://jsbin.com/ruzudututo/edit?html,output for demo of the below script. Maybe not the right forum to request a review, but since started here, would appreciate any constructive criticism.

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Testing</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js" type="text/javascript"></script>
<style type="text/css">
.hidden{display:none;}
a{border: 1px solid black;margin:4px;padding:2px;}
</style>
<script type="text/javascript">
$.getDimensions=function (e,p) {
/*Since I am using jQuery to get element dimensions, make this a jQuery utility method.
Consider not using jQuery!
Future. Allow user to pass those variables desired, and only return those to improve performance.
Assumes BODY is never hidden
*/
var hidden=[], style, $e=$(e);
while(e.parentNode.tagName!='HTML') {
style=e.currentStyle?e.currentStyle:getComputedStyle(e,null);
if((style.display=='none')) {
hidden.push({'e':e,'position':style.position,'visibility':style.visibility,'display':style.display});
e.style.position='absolute';
e.style.visibility='hidden';
e.style.display='block';
}
e = e.parentNode;
}
/* Change to use native JavaScript.
If changes to accept desired attributes instead of all, using the following:
var results={}; for (var i = p.length; i > 0; --i) {results[p[i-1]]=this[p[i-1]]();}
*/
var results={
width:$e.width(),
height:$e.height(),
innerWidth:$e.innerWidth(),
innerHeight:$e.innerHeight(),
outerWidth:$e.outerWidth(),
outerHeight:$e.outerHeight(),
outerWidthTrue:$e.outerWidth(true),
outerHeightTrue:$e.outerHeight(true),
};

//Set it back to what it was
for (var i = hidden.length; i > 0; --i) {
hidden[i-1].e.style.position=hidden[i-1].position;
hidden[i-1].e.style.visibility=hidden[i-1].visibility;
hidden[i-1].e.style.display=hidden[i-1].display;
}
return results;
}

function getDimensionsNormal(e) {
var $e=$(e);
return {
width:$e.width(),
height:$e.height(),
innerWidth:$e.innerWidth(),
innerHeight:$e.innerHeight(),
outerWidth:$e.outerWidth(),
outerHeight:$e.outerHeight(),
outerWidthTrue:$e.outerWidth(true),
outerHeightTrue:$e.outerHeight(true),
};
}

$(function(){
console.log($.getDimensions(document.getElementById("a1")));
console.log(getDimensionsNormal(document.getElementById("a2")));
});
</script>
</head>

<body>
<div class="hidden"><div><p class="hidden"><span class="hidden"><a id="a1" href="#">hello</a></span></p></div></div>
<div><div><p><span><a id="a2" href="#">hello</a></span></p></div></div>
</body>
</html>

jQuery: Get height of hidden element in jQuery

You could do something like this, a bit hacky though, forget position if it's already absolute:

var previousCss  = $("#myDiv").attr("style");

$("#myDiv").css({
position: 'absolute', // Optional if #myDiv is already absolute
visibility: 'hidden',
display: 'block'
});

optionHeight = $("#myDiv").height();

$("#myDiv").attr("style", previousCss ? previousCss : "");

how to get width of element that appear on hover

hide and show your element using opacity: 0 & opacity: 1.

display: none property is hide your element with its occupied space. that's why you are not getting width of your element.

alert("width is"+document.getElementById('spandiv').offsetWidth);
.wrapper > input { display: block; margin-left: auto; margin-right: auto; background-color: pink;
}.wrapper > p { text-align: center; opacity: 0;}
.wrapper > input:hover + #spandiv { background-color: grey; opacity: 1; text-align: center; padding: 5px; color:white; font-weight: normal; overflow: hidden;}
<h1>Test</h1><div class="wrapper"> <input type="text"> <p id="spandiv">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat pulvinar, at pulvinar felis blandit. Vestibulum volutpat tellus diam, consequat gravida libero rhoncus ut.</p> </div>

How to get the overflowed width of an element in a webpage

document.getElementById('parent').scrollWidth

scrollWidth is an IE extension that historically was less well supported than offsetWidth. However nowadays all the modern desktop browsers include it.



Related Topics



Leave a reply



Submit