Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOM Element Width before Appended to DOM

I'm sure the answer is no, but is it possible to determine the width of an element before it is appended to the DOM?

Once it's appended, I know I can use offsetWidth and offsetHeight.

Thanks

like image 456
Steve Avatar asked May 27 '10 13:05

Steve


People also ask

How do you find the width of a DOM element?

Use offsetWidth & offsetHeight properties of the DOM element to get its the width and height.

How do you know if an element is attached to DOM?

To check if an element is connected or attached to the DOM or the document object ( or otherwise called the context ), you can use the isConnected property in the element's object in JavaScript. The isConnected element property returns boolean true if it connected to the DOM ( document object) and false if not.


2 Answers

The trick is to show the element (display:block) but also hide it (visibility:hidden) and to set it’s position to absolute so that it doesn’t affect the page flow.

The MooTools Element.Measure class does this, as Oscar mentioned.

like image 88
Steve Avatar answered Sep 19 '22 17:09

Steve


The Mootools Element.Measure functionality that Oscar mentioned is awesome. For those that use jQuery, here's a quick plugin that accomplishes the same thing:

$.fn.measure = (fn)->   el = $(this).clone(false)   el.css     visibility: 'hidden'     position:   'absolute'   el.appendTo('body')   result = fn.apply(el)   el.remove()   return result 

You can call it like this, making sure to return the value (thanks Sam Fen for pointing that out!):

width = $('.my-class-name').measure( function(){ return this.width() } ) 
like image 27
2 revs Avatar answered Sep 17 '22 17:09

2 revs