Building your own Disqus Recent Comments Widget
Oct 7 |
This article will show you a way to use the Disqus API key to build your own custom recent comments Disqus widget. Do you really need your own custom Disqus Recent Comments Widget?A recent comments widget is a tool that allows blog owners to show the most recent comments on a page. If you're just using Disqus on a static site that does not contain all of the blog entries, you might not need to roll your own custom recent comment widget. And, even if you do have a page that contains all of the blog entries, you may not need a custom widget- Disqus already provides one. To incorporate it, all that you need to do is replace the 'gregorys-blog' string with your own Disqus Blog Identifier (also known as the blog short name) like so:
<script type="text/javascript" src="https://gregorys-blog.disqus.com/recent_comments_widget.js?num_items=10&hide_avatars=0&avatar_size=40&excerpt_length=100"></script >
This is a basic widget, and it contains nearly everything that you may need. My code falls back to this approach in Galaxie Blog when the blog owner does not paste in his own API Key. However, it is not flexible. It is what you see is what you get, and I wanted to blend the recent comment widget with Galaxie Blogs themes, and needed other things, such as having to use the Disqus API to have my own statistical reporting. I'm a stickler for design- I personally determined from the outset that I need roll my own Disqus recent comments widget, and I'll share my approach... Building your own Disqus Recent Comments Widget
- First, you will need to obtain a Disqus Blog Identifier (aka Blog Short Name) and a Disqus API Key. If you don't already have these keys, the following articles should help you in getting these:
- The code below is the style sheets that I developed for Galaxie Blogs recent comments. There is nothing interesting to note here but I am sharing to give you a starting point:
<!-- Styles for disqus -->
<style>
.userProfile {
margin: 15px 0;
list-style-type: none;
clear: both;
}
img.disqusAvatar {
width: 64px;
height: 64px;
float: left;
position: relative;
z-index: 99;
border: 0px;
margin: 0px;
/* The padding needs to be uniform, otherwise the avatar circle will be elongated */
padding: <cfoutput>#avatarPadding#</cfoutput>;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,0.2);
-moz-box-shadow: 0 1px 2px rgba(0,0,0,0.2);
box-shadow: 0 1px 2px rgba(0,0,0,0.2);
overflow: hidden;
}
#disqusCommentDiv a {
overflow: hidden; /* Prevent wrapping */
}
#disqusCommentDiv p {
display: inline; /* Prevent wrapping */
}
#disqusCommentPanel a {
overflow: hidden; /* Prevent wrapping */
}
#disqusCommentPanel p {
display: inline; /* Prevent wrapping */
}
.comment-avatar img {
width: 100%;
height: 100%;
}
</style>
- The real magic happens in the javascript below. I'll try to walk you through some of the more interesting tidbits
- The getRecentDisqusComments function makes a call to the Disqus API invoking the listsPosts method
- Additionally, the related=thread argument is appended to the URL string. This argument allows us to get the URL and Title of the post. Without this argument, we would need to make another call the threads list method, which is frankly a nightmare1.
- We are passing our Disqus keys in the Ajax post
- The getDisqusCommentsResponse callback method retrieves the data and writes out our custom HTML. Here, I am using my own custom class definitions to make the widget blend in with my own themes.
- The isOdd method assists in creating alternate colors of each row.
- The timeSince method is used to append a string to tell the viewer when the comment was made (ie '20 seconds ago').
- Finally, the truncateString method is used to truncate the comment string.
function getRecentDisqusComments(){
// Submit form via AJAX.
$.ajax(
{
type: "get",
url: "https://disqus.com/api/3.0/forums/listPosts.json?related=thread",
data: {
// Passing my own keys.
api_key: "<cfoutput>#application.disqusApiKey#</cfoutput>",
forum: "<cfoutput>#application.disqusBlogIdentifier#</cfoutput>",
limit: "<cfoutput>#numComments#</cfoutput>"
},
// jsponp is supported as well.
dataType: "json",
cache: false,
success: function(data) {
setTimeout(function () {
// Callback function
getDisqusCommentsResponse(data);
// The timeout ensures that the data will be available to the callback function.
}, 250);
}
}
);
}//..function getRecentDisqusComments(){
function getDisqusCommentsResponse(data){
var html = "";
// Loop through the json structure.
for (var i = 0, len = data.response.length; i < len; i++) {
// Isolate our post (or entry).
var post = data.response[i];
// Set a current row value from our index. I need a whole number to determine the alternating row color. I could just use [i]+1, but I am setting this for readability.
var row = parseInt([i]);
// Get the data for the post.
var authorName = post.author.name;
var authorProfileUrl = post.author.profileUrl;
var authorAvatarUrl = post.author.avatar.cache;
// We need to strip the HTML out of the comment. It has links that are not useful and will take up our space.
var comment = stripHtml(post.message);
var commentPromoted = post.isHighlighted;
var approved = post.isApproved;
// Get the timestamp and convert it into a proper js date object.
var created = new Date(post.createdAt);
// Find the link to the actual article. Note: for this to work, you must have related=thread appended to the ajax link (ie https://disqus.com/api/3.0/forums/listPosts.json?related=thread).
var pageLink = post.thread.link;
var pageTitle = post.thread.title;
// Create the HTML. We will try to keep this nearly identical to the recent comment widget, but put in our own kendo classes here.
// Crete the table on the first row.
if (row == 0){
html += '<table id="disqusComment" align="center" class="k-content fixedPodTableWithWrap" width="100%" cellpadding="0" cellspacing="0">';
}
// Create the row and alternate the k-content and k-alt class.
if (isOdd(row)){
html += '<tr class="k-alt" height="50px;">';
} else {
html += '<tr class="k-content" height="50px;">';
}
// After the first iteration, create a row with a border. Javascript arrays (which is our 'row') start at 0.
if (row == 0){
html += '<td align="left" valign="top" class="userProfile">';
} else {
html += '<td align="left" valign="top" class="border userProfile">';
}
// Wrap the avatar with the authors profile link
html += '<br/><a href="' + authorProfileUrl + '" aria-label="Profile for ' + authorName + '" rel="nofollow noopener">' + authorName;
// Place the avatar into the cell and close the anchor link.
html += '<img class="disqusAvatar" src="' + authorAvatarUrl + '" aria-label="Profile for ' + authorName + '"></a><br/>';
// Add the comment. The comment is already wrapped with a paragraph tag.
html += truncateString(comment, <cfoutput>#lenComment#</cfoutput>) + '<br/>';
// Create the HTML to insert into the page title.
html += '<a href="' + pageLink + '" aria-label="' + pageLink + '">' + pageTitle + '</a> - ';
// Add the timestamp to quickly identify how recent the post is.
html += timeSince(new Date(created)) + ' ago<br/>';
// Close the cell and the row.
html += '</td></tr>';
// Close the table on the last row
if (row == <cfoutput>#round(numComments-1)#</cfoutput>){
html += '</table>'
}
// Append the html to the page.
$(document).ready(function() {
$("#recentCommentsDiv").html(html);
$("#recentCommentsPanel").html(html);
});
}//..for (var i = 0, len = data.response.length; i < len; i++) {
}
// Helper function to determine if the number is even or odd. This is used to create alternating row colors.
function isOdd(num) {
return num % 2;
}
function stripHtml(html){
html.replace(/<[^>]*>?/gm, '');
return html;
}
// Function to write out the time since the post.
// Source: https://stackoverflow.com/questions/3177836/how-to-format-time-since-xxx-e-g-4-minutes-ago-similar-to-stack-exchange-site
function timeSince(date) {
var seconds = Math.floor((new Date() - date) / 1000);
var interval = Math.floor(seconds / 31536000);
if (interval > 1) {
return interval + " years";
}
interval = Math.floor(seconds / 2592000);
if (interval > 1) {
return interval + " months";
}
interval = Math.floor(seconds / 86400);
if (interval > 1) {
return interval + " days";
}
interval = Math.floor(seconds / 3600);
if (interval > 1) {
return interval + " hours";
}
interval = Math.floor(seconds / 60);
//alert(interval + ' minutes date: ' + date);
if (interval > 1) {
return interval + " minutes";
}
return Math.floor(seconds) + " seconds";
}
truncateString = function(str, length, ending) {
if (length == null) {
length = 100;
}
if (ending == null) {
ending = '...';
}
if (str.length > length) {
return str.substring(0, length - ending.length) + ending;
} else {
return str;
}
};
// Call the method to populate the recent comments.
getRecentDisqusComments();
If you have any questions, don't hesitate to ask. Happy commenting! Further Reading: 1Raymond Camden has an excellent article at https://www.raymondcamden.com/2014/03/21/Example-of-a-JavaScript-Disqus-Recent-Comment-Widget. I wished that I had read this earlier before going down my own rabbit hole. To get the related post, I initially tried to call the thread list method (at https://disqus.com/api/3.0/threads/list.json) within a nested ajax post. My initial code was just... ugly. Finally, I stumbled upon this article and found out that I could simply use the related=thread argument to attach the comment to a thread.
Related Entries
Tags
Disqus IntegrationThis entry was posted on October 7, 2019 at 11:06 PM and has received 2090 views.