Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created January 7, 2022 13:16
Showing A Comment Preview As You Type On This Blog
var previewTimer = null;
var previewRequest = null;
var lastPreviewTarget = null;
var previewSection = form.find( ".comment-preview" )
var previewContent = previewSection.find( ".comment-preview__content" );
var errorContent = previewSection.find( ".comment-preview__error" );
// I handle keydown events on the comment intake.
comment.keydown(
function handleKeydown( event ) {
// Debounce typing so that we aren't triggering an AJAX request after
// every single keypress.
clearTimeout( previewTimer );
previewTimer = setTimeout( showCommentPreview, 300 );
}
);
// I render the HTML preview for the current Markdown comment.
function showCommentPreview() {
var commentMarkdown = $.trim( comment.val() );
// Since this call is, in part, being triggered by key-events, we want to
// make sure that something has actually changed. If the users is moving
// around the comment using arrow-keys (for example), we have no need to
// update the comment preview.
if ( lastPreviewTarget === commentMarkdown ) {
return;
}
lastPreviewTarget = commentMarkdown;
// If the user cleared the comment form, hide the preview rendering.
if ( ! commentMarkdown ) {
previewSection.removeClass( "comment-preview--active" );
return;
}
// Since the AJAX calls are all asynchronous, there's a good chance that
// we'll end up with multiple, concurrent calls. Kill the last one so that
// we don't end-up processing the responses out-of-order.
if ( previewRequest ) {
previewRequest.abort();
previewRequest = null;
}
previewRequest = $.ajax({
type : "post",
url : "/index.cfm",
data : {
event: "api.blog.previewComment",
content: commentMarkdown
},
dataType: "json"
});
// NOTE: We have to break-up the AJAX request from the Promise chain since
// the resultant promise won't have an .abort() method on it - that's only
// returned on the AJAX response object (for backwards compatibility).
previewRequest.then(
function handleSuccess( response ) {
previewRequest = null;
previewSection.addClass( "comment-preview--active" );
previewContent.html( response.preview ).show();
errorContent.hide().empty();
},
function handleError( response ) {
if ( response.statusText === "abort" ) {
return;
}
previewRequest = null;
previewSection.addClass( "comment-preview--active" );
previewContent.hide().empty();
errorContent.text( response?.responseJSON?.message || "Something went wrong - the comment preview cannot be rendered." ).show();
}
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment