Change a div's height to auto using jQuery once the div reaches a certain height

48,701

Solution 1

This will only run ONCE when the document is ready. You need to put it inside a resize() event handler:

$('#upload3').resize(function() {
  if($(this).height() > 400){ $(this).css('height','auto'); }  });
});

Solution 2

You need to bind resize event of the div

$(document).ready(function(){

$("#upload3").bind("resize", function() {
   if($('#upload3').height() > 400){ $('#upload3').css('width','auto'); }
});

});

Solution 3

That if statement is only going to run when the document is ready. If you want to do something when something else happens (an event!), you need an event handler.

Also, in your example, you're setting the width to auto, not the height.

But really, you don't need javascript to do this, you can simply set a minimum height in CSS. When the content overflows the minimum height, the block will stretch to fit the content as if there was no height set.

Example:

#upload3 {
    min-height: 400px;
}
Share:
48,701
Admin
Author by

Admin

Updated on June 10, 2020

Comments

  • Admin
    Admin almost 4 years

    I have a div that lets the user add additional form inputs dynamically. I'd like to be able to change this div's height to auto once it reaches a certain height. Here is the jQuery code I have, though it doesn't seem to be working at the moment.

    $(document).ready(function(){
    if($('#upload3').height() > 400){ $('#upload3').css('width','auto'); }  });
    
    • thirtydot
      thirtydot almost 13 years
      Are you trying to change the height or the width to auto? Your description and code do not match.