Domanda

I created a jquery code which lets you click on a button to show or hide a div. However, when I toggle the div the container shifts a bit while it opens. I googled, and everywhere it says the expanding div is losing it's height. How do I fix it? I can't set a height to that div because inside the div I have more expanding content, like little paragraphs where you click "read more" and then more text appears, so the height of the expanding div is always changing.

This is my code:

<script type="text/javascript">
    $(window).load(
      function ()
      {
        $(".expandbutton").click(
          function ()
          {
            $("#mainexpand").toggle("fast");
          }
        );
      }
    );
</script> 

So how do I prevent the content from moving around when you click the .expandbutton div to toggle the #mainexpand div?

È stato utile?

Soluzione

$(document).ready(function(){
  $("#mainexpand").hide();

 $( ".expandbutton" ).click(function() {

  if($("#mainexpand").is(":visible")){
    $("#mainexpand").hide();
  } 
   else {
   $("#mainexpand").show();
  }

 });
 });

Altri suggerimenti

You need to set visibility instead of displaying or hinding it with display:

$(window).load(function(){
 $( ".expandbutton" ).click(function() {
  if($("#mainexpand").css("visibility") == "visible"){
    $("#mainexpand").css("visibility","hidden");
  } else {
   $("#mainexpand").css("visibility","visible");
  }
 });
 });
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top