Francesco Mari
Francesco Mari

Reputation: 1738

How to detect div height after its content is loaded via ajax with jquery

I've got this strange problem: I got two divs, a menu and a content

<div id="menu">
  <a href="#" id="link1"> Link </a>
  <a href="#" id="link2"> Link </a>
</div>

<div id="content">
</div>

When you click on a link, the div is loaded with the content of different html files:

$('#link1').click(function() {
  $('#content').load('page1.html');
}
$('#link2').click(function() {
  $('#content').load('page2.html');
}

...and it works :-)

This way the #content changes its height because it is "filled" with the html files, and I want that #menu takes the same height of #content, so I appended

$("#menu").height($("#content").height());

on the click() functions, but the height of the #content is calculated before loading the files, so it doesn't work. How can I detect when the content is loaded and do the resize after that?


PS: The problem is also on page loading: I added

$('#prod1').click();

within $(window).load, to simulate a click on the first menu item; #content is filled correctly, but the height is miscalculated.. I tried to debug with console.log, tracing the height of the div, but it gave 0, although i put it after the load function.

The only (bad) solution was to use the setInterval function, watching continuously the #content's height and set the same height on the #menu.

Upvotes: 3

Views: 1380

Answers (2)

Ram
Ram

Reputation: 144689

You can use the callback function:

$('#link1').click(function(e) {
   e.preventDefault();
   $('#content').load('page1.html', function(){
      // ...
   });
});

However, if you are loading images, you have to listen to the load event that is fired for those images, otherwise the height is calculated incorrectly, there are several plugins that you can use like imagesLoaded.

Upvotes: 3

dinodsaurus
dinodsaurus

Reputation: 5095

i think you should do something like this $("#menu").css('height', $("#content").height() + 'px'); You need to apply this after the #content is loaded

Upvotes: -1

Related Questions