I am getting some html and inserting it with .html()
, after which I am trying to get the width of one of newly inserted elements with .width()
(which h
If the element is an image, then the width()
and height()
methods should be accessed on the .load()
jQuery handler;
If the element is a DOM subtree, then they should be accessed on the .ready()
handler.
The reason is that you can't rely on what jQuery reports to be the size of the element until the element has actually been loaded.
We found out that document.ready was not good enough so 300ms worked well:
setTimeout(function() {
resizeHeightOfMyDiv();
$(window).on("resize", function() {
resizeHeightOfMyDiv();
});
}, 300);
Depends on what browser. Occasionally I find something will break with the synchronous rendering expectations of the javascript runtime and I'll need to get the result on the next tick.
I'd try:
$(elem).html(data);
setTimeout(function(){
// Get the width here
},0);
jQuery will return a zero width if the element is not visible. For example, I was having the same issue with an item being inserted onto a hidden form tab. Temporarily assigning it to the body, where it was visible, I was able to determine the width:
$("body").append(el); // First assign it to the body so that it's visible
var width = el.width(); // The width will now be correct
wrapper.append(el); // Now place the element where you want it.
One caveat is that if the element inherits different styling when assigned to the body then the width may not be correct.
// ...
$('.box', boxOutput).each(function(i) {
//boxWidth += $(this).width(); /* this is where sometimes width returns 0 */
boxWidth += this..getBoundingClientRect().width;
});
//...
Not sure 100% but I think that your problem is that the code called outside the function where you attach the elements doesn't recognize the newly created elements. A quick example:
<div id="container">
</div>
<script>
$(document).ready(function() {
$('#container).html('<p style="width:200px">Lorem ipsum</p>');
alert($('#container p').width()); // alerts 0
$('#container p').html('Lorem ipsum dolor sit amet'); // if content doesn't change, it's clearly a problem of jquery not being able to bind the functions to your new elements
});
</script>
If you can tell us what you're doing exactly we'll surely find a solution.
LATER EDIT
Now that you posted code, I can actually help. You need to run this code:
$('.box', boxOutput).each(function(i) {
boxWidth += $(this).width(); /* this is where sometimes width returns 0 */
});
in the function in your ajax response function. Example:
$.get('script.php', function(data) {
$('#elem').html(data);
// your code for width()
});
Hope this helps.