Find the "potential" width of a hidden element

Viewed 45018

I'm currently extending the lavalamp plugin to work on dropdown menus but I've encountered a small problem. I need to know the offsetWidth of an element that is hidden. Now clearly this question makes no sense, rather what I'm looking for is the offsetWidth of the element were it not hidden.

Is the solution to show it, grab the width, then hide again? There must be a better way...

11 Answers

If you know the element to be the full width of a parent element another approach is to create a recursive method:

es5:

var getWidth;
getWidth = function($el){
  return $el.offsetWidth || getWidth($el.parentElement);
}
var width = getWidth(document.getElementById('the-element'));

es6:

let getWidth
getWidth = ($el) => $el.offsetWidth || getWidth($el.parentElement)

const width = getWidth(document.getElementById('the-element'))
 var $hiddenElement = $('#id_of_your_item').clone().css({ left: -10000, top: -10000, position: 'absolute', display: 'inline', visibility: 'visible' }).appendTo('body');
 var width = parseInt($hiddenElement.outerWidth());
 $hiddenElement.remove();

Sorry I am late to this conversation. I am surprised no one has mentioned getComputedStyle. (Note this only works if the CSS sets a width value) Grab the element:
let yourEle = document.getElementById('this-ele-id');

and use the function:
getComputedStyle(yourEle).width

This returns a string so you will have to remove the numbers from the string. This works even when the element's display style is set to none.

Other articles to read about this includes here at zellwk.com

Related