views:

23

answers:

2

I'm having trouble getting the following JQuery script to function properly - its functionality is as follows:

1) Hide the content below each headline

2) Upon clicking a headline, substitute the "#first-post" with the headline + the hidden content below the headline.

I can only seem to get the script to clone the headline itself to #first-post, not the headline + the content beneath it. Any idea why?

<HTML>
<HEAD>
  <script src="http://code.jquery.com/jquery-latest.js"&gt;&lt;/script&gt;
</HEAD>
<script>
$(document).ready(
function(){ 
$('.title').siblings().hide();
$('.title').click( function() {
$('#first-post').replaceWith($(this).closest(".comment").clone().attr('id','first-post'));
$('html, body').animate({scrollTop:0}, 'fast');
return false;
});
});
</script>
<BODY>
<div id="first-post"> 
  <div class="content"><p>This is a test discussion topic</p> </div> 
</div>
<div class="comment"> 
<h2 class="title"><a href="#1">1st Post</a></h2> 
  <div class="content">
    <p>this is 1st reply to the original post</p> 
  </div> 
  <div class="test">1st post second line</div>
  </div>
<div class="comment"> 
<h2 class="title"><a href="#2">2nd Post</a></h2> 
  <div class="content"> 
    <p>this is 2nd reply to the original post</p> 
      </div> 
  <div class="test">2nd post second line</div>
  </div> 
</div>
<div class="comment"> 
<h2 class="title"><a href="#3">3rd Post</a></h2> 
  <div class="content"> 
    <p>this is 3rd reply to the original post</p> 
  </div> 
  <div class="test">3rd post second line</div>
    </div> 

</div>

</BODY>
</HTML>
+1  A: 

You need to show the hidden elements as well. Note that replaceWith returns the removed element, so you need to requery for the new "first-post" element, then it's hidden descendants, when doing the show.

$('.title').click( function() {
    $('#first-post').replaceWith($(this).closest(".comment").clone().attr('id','first-post'));
    $('#first-post').find(':hidden')
                   .show();
    $('html, body').animate({scrollTop:0}, 'fast');
    return false;
});
tvanfosson
Thanks! Fixed the problem :) Out of curiosity, why isn't $('#first-post).show(); enough? Why do we need to find the hidden selectors first?
HipHop-opatamus
@HipHop: Because it's not the #first-post element that is hidden. Calling `show` on an element doesn't show hidden children.
Guffa
+1  A: 

You are cloning the hidden elements, so the copies are also hidden. Add a call to show() in there.

Guffa