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
Use offsetWidth & offsetHeight properties of the DOM element to get its the width and height.
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.
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.
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() } )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With