Hi all,
I already [posted this question on Stack Overflow]) but unfortunately got no answers.
I’m using jQuery on my WordPress blog to ajaxify comments and it basically works as expected – apart from two things. So first, here’s the code I’m working with:
$( ‘#commentform’ ).submit(function() {
var button = $(‘#submit’),
respond = $(‘#respond’),
commentlist = $(‘.comment-list’),
cancelreplylink = $(‘#cancel-comment-reply-link’);
if ( !button.hasClass( ‘loadingform’ ) ) {
$.ajax( {
type: ‘POST’,
url: comment_params.ajaxurl,
data: $(this).serialize() + ‘&action=ajaxcomments’,
beforeSend: function(xhr) {
// what to do just after the form has been submitted
button.addClass(‘loadingform’).val(‘Loading …’);
},
success: function ( addedCommentHTML ) {
// if this post already has comments
if( commentlist.length > 0 ) {
// if in reply to another comment
if( respond.parent().hasClass( ‘comment’ ) ) {
// if this comment already has replies
if( respond.parent().children( ‘.children’ ).length ) {
respond.parent().children( ‘.children’ ).append( addedCommentHTML );
} else {
// if no replies
addedCommentHTML = ‘<ul class=”children”>’ + addedCommentHTML + ‘</ul>’;
respond.parent().append( addedCommentHTML );
}
// close respond form
cancelreplylink.trigger(“click”);
} else {
// simple comment
commentlist.append( addedCommentHTML );
$(“html”).animate({scrollTop: $( addedCommentHTML ).offset().top}, 800);
}
} else {
// if no comments yet
addedCommentHTML = ‘<ul class=”comment-list”>’ + addedCommentHTML + ‘</ul>’;
respond.before( $(addedCommentHTML) );
}
// clear comment textarea
$(‘#comment’).val(”);
},
complete: function() {
// what to do after a comment has been added
button.removeClass( ‘loadingform’ ).val( ‘Post comment’ );
}
});
}
return false
}),
Problem 1: *cancelreplylink.trigger(“click”)* isn’t working. This code is supposed to close the comment form (div with id cancel-comment-reply-link) that pops up after you click reply on a comment. I have no idea why it’s not doing that.
Problem 2: I want the page to scroll to the new comment after submitting, however, this line scrolls to the top of the page instead:
`$(“html”).animate({scrollTop: $( addedCommentHTML ).offset().top}, 800);`
When replacing the code with
`$(“html”).animate({scrollTop: $( ‘.comment-list li:last-child’ ).offset().top}, 800);`
it also doesn’t work but just scrolls a few pixels down. What I’d expect instead is the page scrolling to the last comment. Here, too, I just can’t figure out why it’s not working.
You can see a live example here: [https://strunk.blog/what-could-possibly-go-wrong/])
Any help is appreciated.
[ad_2]