Reputation: 1520
i have create a div class=box via Ajax call and appended to an main div. This div class=box change its height based on its content. I need to have its height but .height() return 0....
$.ajax({ url: "json/news.json",
dataType: "json",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(data){
var html ="<div class='box'>"+data.box+"</div>";
}
});
// now i want its height
var j = $('.box').height();
Any suggestion? Thanks
Upvotes: 1
Views: 12803
Reputation: 4045
Try that http://api.jquery.com/outerHeight/
var j = $('.box')outerHeight();
Upvotes: 0
Reputation: 16009
There are 2 problems here:
$.ajax
is asynchronous, so it does not create anything until the success
callback has run. If you want to measure your box, you will need to do it in the callback:
$.ajax({ url: "json/news.json",
dataType: "json",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(data){
var html ="<div class='box'>"+data.box+"</div>";
var j = $('.box').height();
}
});
You are not adding your html to anything, and as it is not part of the DOM it will not have a height. You need to do something like the below:
success: function(data){
var html ="<div class='box'>"+data.box+"</div>";
$("body").html(html);
var j = $('.box').height();
}
Upvotes: 5
Reputation: 817128
The last line of your code is executed before the ajax cal returns. Put the code that needs the height in the callback (and actually add the HTML to the document):
$.ajax({ url: "json/news.json",
dataType: "json",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(data){
var html ="<div class='box'>"+data.box+"</div>";
var height = $(html).appendTo('body').height();
}
});
Upvotes: 2