Ste
Ste

Reputation: 1520

Get height of a div dynamically created

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

Answers (3)

Yasen Zhelev
Yasen Zhelev

Reputation: 4045

Try that http://api.jquery.com/outerHeight/

var j = $('.box')outerHeight();

Upvotes: 0

Steve Greatrex
Steve Greatrex

Reputation: 16009

There are 2 problems here:

  1. $.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();
      } 
    });
    
  2. 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

Felix Kling
Felix Kling

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

Related Questions