I have a comment page that has a reply and cancel reply button. Using the following code when the reply button is clicked the cancel reply button will appear instead. There is only one problem, when the reply button of one comment is clicked, without clicking the cancel reply button of that comment I click the reply button of another comment, the reply button of the previous comment disappears. My level of knowledge of JavaScript is low. The code above solves all my needs, there is only one problem that I said, the code should be edited so that it does not destroy my other needs.
<script>
jQuery( function( $ ){
$( '.comment-reply-link' ).on( 'click', function(){
var commentContainer = $(this).closest('.comment_container');
commentContainer.find('.comment-reply-link').hide();
$( '#cancel-comment-reply-link' ).insertAfter( this ).show();
} );
$( '#cancel-comment-reply-link' ).on( 'click', function(){
var commentContainer = $(this).closest('.comment_container');
commentContainer.find('#cancel-comment-reply-link').insertAfter(this).hide();
commentContainer.find('.comment-reply-link').show();
} );
} );
</script>
2
Answers
I think it’s because you’re using an id
'#cancel-comment-reply-link'
Try instead of unsing a id like
TO
Because an id is unique to a DOMelement according to MDN.Mozilla
And change the script to:
If I understand correctly, the issue you are facing is the following:
If the above is the case, the issue is that you’re not "unhiding" the first "Reply" button clicked (in step 1), when you click the second "Reply" button in step 2.
There are a few ways you can fix this. One quick way is just showing the
.comment-reply-link
before you call$( '#cancel-comment-reply-link' ).insertAfter( this ).show();
Something like:
Other ways are applying some sort of "state" to the reply element (a class, data attribute), and querying that (to show when you click another reply later).