Yax
Yax

Reputation: 2189

How to hide loaded comments in jQuery

I have a jQuery code that loads More comments of a post via AJAX. The More comments is afterward replaced with Less comments which is expected to hide the loaded comments but it is not working...

This is the HTML code:

<div class = 'feeds'>
  <div class = 'comments'>
    <div class = 'comment_data>
      <div class = 'per_comment'>
        <p> slideToggle!</p>
      </div>
      <div class = 'per_comment'>
        <p> classToggle!</p>
      </div>
    <button class='morecomments' value='7' name = 'more' type='submit'>
     More comments</button>
  </div>
 </div>
</div>

jQuery code that loads more comments, and it works just fine:

$(".morecomments").click(function () {
  var $this = $(this);
  var post_id = $(this).val();
  var request = $.ajax({
  url: "comments.php",
  type: "POST",
  data: { post : post_id },
  dataType: "html"
  });
request.done(function( msg ) {
   $this.prev('.per_comment').html( msg ); 
   $this.replaceWith("<button class='lesscomments value='7' name = 'less'   type='submit'>Less comments</button>"); 
});
});  

jQuery code that I expect to hide the loaded comments but it is not working:

$( ".lesscomments" ).click(function() {
var $this=$(this);
$(".murconform").submit(function(e){
        return false;
    });
    $this.prev('.comment_data').slideToggle('fast')
});

Anticipatory thanks.

Upvotes: 0

Views: 167

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

Because the less comments element is created dynamically, you need to use event delegation

//this should not be within the less handler.... need to handle the logic in some other way
$(".murconform").submit(function (e) {
    return false;
});
$('.comment_data').on('click', ".lesscomments", function () {
    var $this = $(this);
    $this.closest('.comment_data').slideToggle('fast')
});

Upvotes: 1

Rafael Soufraz
Rafael Soufraz

Reputation: 964

This happens because the lesscomments element does not exist in the page when it is loading.
And you should be using document.ready to eetuar action.
Try to use the function on: http://api.jquery.com/on/

Upvotes: 1

Related Questions