mheavers
mheavers

Reputation: 30158

javascript/jquery - how to get the width of an element / css class that hasn't been added to dom yet

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?

Upvotes: 6

Views: 5272

Answers (2)

Eamonn
Eamonn

Reputation: 868

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.

Upvotes: 0

Raghav
Raghav

Reputation: 1064

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"

Upvotes: 1

Related Questions