Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
94
rated 0 times [  97] [ 3]  / answers: 1 / hits: 24312  / 13 Years ago, wed, june 1, 2011, 12:00:00

With the code below, the alert doesn't return the actual size of #main, it always returns the value of #main's css width with the % dropped. So in this case I get 95 in the alert. If I alert parent().width() I get 100.



The data returned from the .get() call is a ul that sometimes is wider than #main, and sometimes not. The width of the content doesn't seem to have any bearing on what .width() returns.



So my question is, how do I get the true pixel width of #main?



CSS:



#container {
width: 100%;
}

#main {
width: 95%;
overflow: hidden;
}


HTML:



<div id=conatiner>
<div id=main></div>
</div>


Javascript/jQuery:



$.get('page.php', function(result) {
$('#main').html(result);
});
alert($('#main').width();

More From » jquery

 Answers
0

I ran into this same issue while trying to implement jquery.autogrow-textarea on textareas used for inline editing. The textareas were contained within div's that were not yet displayed (css display: none;). While debugging the .autogrow() javascript code, I discovered that jQuery's .width() was returning the percentage value with the '%' character removed as opposed to the calculated width in pixels (e.g. 100 for 100%, 80 for 80%).



Here is the jsfiddle that illustrates this scenario: http://jsfiddle.net/leeives/ujE6s/



To work around this, I changed my code to .autogrow() as soon as the textarea was displayed instead. The calls to .width() were then accurate.



I'm not sure if you're working with hidden content or not, but thought I'd write up my answer in case others stumbled upon this (like I did) while searching for an issue with jQuery's .width().


[#91915] Tuesday, May 31, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alfonsok

Total Points: 386
Total Questions: 101
Total Answers: 90

Location: Puerto Rico
Member since Sun, Jun 27, 2021
3 Years ago
alfonsok questions
Sat, Jun 5, 21, 00:00, 3 Years ago
Wed, Jun 2, 21, 00:00, 3 Years ago
Mon, Oct 5, 20, 00:00, 4 Years ago
;