I have the following code which works but it becomes a bit jumpy at the end of each toggle action.
Will it be smoother if I toggle the paragraph? I am trying to get the paragraph, but I don't know how to do it.
<head>
<style type="text/css">
body {width: 660px; margin: 0 auto; }
.toppara{
background-color: #FF9;
}
.morepara {
background-color: #fff;
display:none;
}
.togglebutn {
color: #900;
background-color: #FFF;
}
</style>
</head>
<body>
<div id="section1">
<div class="toppara"><p>Content 1.</p>
</div>
<div class="morepara">
<p>
Content 2.
</p>
</div>
<p class="togglebutn">
<a>Show/Hide</a>
</p>
</div><!-- section 1 -->
<!-- section 2 -->
<div id="section2">
<div class="toppara"><p>Content 3.</p>
</div>
<div class="morepara">
<p>
Content 4.
</p>
</div>
<p class="togglebutn">
<a>Show/Hide</a>
</p>
</div><!-- section 2 -->
<script language="javascript" type="text/javascript">
$(function() {
$('.togglebutn a').click(
function(){
var $parentpara = $(this).parent().prev();
$parentpara.toggle('slow');
});
});
</script>
For sliding down to work JQuery has to guess the eventual height of the element. When it gets this wrong you see a jump when the animation ends and the element is allowed to find its natural height.
Your problem is caused by the margins on the p
tag which take up space in JQuery's original estimate, but are collapsed when the animation completes.
The solution is to either remove the margins on the p
tags, to try to prevent the collapsing from happening by giving the .morepara div an explicit height, a border or some top/bottom padding, though both options have undesirable side effects.