6

I'm trying to dynamically find the width of an item which will have a css class with a specific width, in order to dynamically position its background image (a sprite). However, the item has not yet been added to the DOM. Is there a way to read a class's width property before it's added to the DOM?

4
  • Not that I know of reliably. A common approach is to add it off screen (-x,-y) and then check it's width. Commented Oct 7, 2011 at 21:57
  • I don't think JavaScript can access the 'physical' properties of an element until it's been added to the DOM; so I don't think this is possible, no... Commented Oct 7, 2011 at 21:58
  • Consensus would say no. I too do not think it is possible. Commented Oct 7, 2011 at 22:02
  • possible duplicate of DOM Element Width before Appended to DOM, Getting the height of an element before added to the DOM Commented Oct 7, 2011 at 22:03

2 Answers 2

1

I believe you cant. Instead add it to a test div,find the width and then remove the div.

   $selector.append("<div id='test'></div>");
   var widthVal= $selector.find("#test").width();
       $("#test").remove();

selector is the element selector you may want to append to. You can associate a class with the "test" div, to have it as "display:none"

Sign up to request clarification or add additional context in comments.

Comments

0

This is a Little Hackie but it should work. Add it to the DOM with the CSS Attribute display: none so it will be invisible then you can read the with property and delete the element if need be after. Or change its state from Display:none.

Hope this helped.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.