BuddyDev

Facebook Style Activity Commenting with BuddyPress

How many of you use facebook for connecting with Friends and family, I believe almost all 🙂 Today, I am going to show how to make the BuddyPress Activity Stream activity commenting look/work like facebook activity commenting. I will be doing it by using bp-default theme as an example. you can easily modify it for other themes.

In addition to writing css/js, we will need one jquery plugin to autogrow the text area as a user types.

Github Repo: https://github.com/sbrajesh/fb-style-activity-commenting

Goals:-

  • Make activity comment section look like facebook
  • make activity posting like facebook

External script required:-


jQuery AutoGrow textArea
:- We will use it for autogrowing comment text box. The script is a part of jQuery grab bag by Jason Frame

Lets get started. But before that, lets have a look at the final screenshot.

Step 1: No multilevel commenting

I know it is a bad decision, but this is what facebook does. I am just following the lead.

You can put the following code in functions.php to stop mulitlevel commenting

[sourcecode language="php"]
add_filter('bp_activity_can_comment_reply','__return_false');
[/sourcecode]

Since I don't want to temper with core files of bp-default(read it whatever theme you use), We will be including the code to load out comment.js and the autogrow textarea plugin. You should create comment.js in the_inc folder of your theme and also put the autogrow plugin there.

Here is the code you need to put in functions.php

[sourcecode language="php"]
//include the javascript, change it as you want
add_action("wp_print_scripts","bp_fbstyle_comment_js");
function bp_fbstyle_comment_js(){
if(!is_user_logged_in())
return ;//we do not want to include the js
wp_enqueue_script("bpfb-comment-js", get_stylesheet_directory_uri()."/_inc/comment.js",array('jquery','jquery-effects-core', 'dtheme-ajax-js'));
wp_enqueue_script("bpfb-comment-autogrow-js", get_stylesheet_directory_uri()."/_inc/jquery.autogrow-textarea.js",array('jquery'));
}

[/sourcecode]

I am including these from my child theme, you can change the above line to make sure you are loading it correctly from your theme.

That's all we need to do in php. Now, we will write some javascript and css to make it work like facebook activity commenting.

Step2:  The CSS

Let us make the activity comment form visible. Onething to note here, facebook puts a visible comment form only for those activities which already have atleast one comment. I am following the same. You can change that behaviour and make it visible for all activities(I will be mentioning how to do that)

I have adjusted the margin of the form appropriately for our page formatting.

[sourcecode language="css"]
li.has-comments div.activity-comments form.ac-form {
display:block;
margin:0 0 5px 0;
}
/*if you want to make it visible for all activity, change the above css selector from 'li.has-comments div.activity-comments form.ac-form' to 'div.activity-comments form.ac-form'. Note, we removed the li.has-comments from the selector*/
[/sourcecode]

Now, as the form is visible, we will need to hide the commenter avatar(the logged in user avatar and remove the unnecessary margin/padding)

[sourcecode language="css"]

.ac-form .ac-reply-avatar{
display:none;
}

div.activity-comments form div.ac-reply-content{
margin-left: 0;
padding-left: 0;
margin-bottom: 5px;
height:35px;/* you may need to adjust height according to the one you choose for your textarea*/
}

[/sourcecode]

That's nice. Now, we will need to fix the height of the textarea to fit one line of text and hide the submit button. After all, we assume pressing enter will post the comment.

[sourcecode language="css"]
div.activity-comments form textarea {
height: 13px;
}
div.activity-comments form input[type='submit']{
display:none;
}

[/sourcecode]

So, that's the basic css. It will make the comment form visible for the appropriate activity entries.

Now, When a particular text area gains focus, we will add class 'active' to its parent form. So, we will need to update our active form css when a comment textarea gains focus.
Here is the css for that

[sourcecode language="css"]
/*on active/focus*/
form.active .ac-reply-avatar{
float:left;
display: block;
}
form.active .ac-reply-avatar img.avatar {
float: left;
margin: 0 3px 0 0;
height: 25px;

width: 25px;
}
/*reset the height of comment box wrapper to make the comment box grow later*/
div.activity-comments form.active div.ac-reply-content{
height:auto;
}
form.active .ac-textarea{
margin-bottom: 10px;
padding: 0px 8px 8px 8px;
}
div.activity-comments form.active div.ac-reply-content{
margin-left: 30px;
padding-left: 2px;

}
[/sourcecode]

So, that is the complete css we will need.

Let us write some javascript code to emulate the fb effect. All these code goes to comment.js

Step 3: The javascript

So, as jQuery says, let us do everything when the dom is ready. All the code blow this section is wrapped inside this block

[sourcecode language="javascript"]
jQuery(document).ready(function(){

//the actual code

});
[/sourcecode]

Now, the initial setup. The BP default theme hides all the activity form using javascript. We will need to make them visible again.

[sourcecode language="javascript"]

var jq=jQuery;//we do no want to keep the value to mess our layout, and we do not want to do the complex calculations too
jq("form.ac-form textarea").val(");

jq(".has-comments form.ac-form").show();//make all the activity comment form visible whose parent have at least 1 previous comment.
//if you want to show the activity comment form for all the activities , irrespective of whether there are already comments or not, comment the above line and uncomment the below line
//jq("form.ac-form").show();
jq("form.ac-form").show();//make all the activity comment form visible
[/sourcecode]

Please note what I mentioned in the last 2 lines of above code. If you have made your css to show the comment form for all the activity entries, then comment and uncomment the above code as instructed.

Now, let us bind the auto grow plugin to all the activity comment text area

[sourcecode language="javascript"]

jq('.ac-textarea textarea').autogrow();

[/sourcecode]

Add class "active" to the parent of the text area which has gained focus and remove the class 'active from all other forms.

[sourcecode language="javascript"]
//on focus, add remove active class
jq('.ac-textarea textarea').live('focus', function(){
var ac_form=jq(this).parent().parent().parent();//parent form
ac_form.addClass('active');

jq('.ac-textarea').parents('form.ac-form').not(ac_form).removeClass('active');

});
[/sourcecode]

The above step could have been done in easier step by first removing the class from all forms and then adding it to current textarea's parent.I just wanted better usability by first activating this form.

Let us handle the Pressing of ESC button and the Enter. We are resetting the form on escape key pressing and posting the comment when the enter key is pressed.

[sourcecode language="javascript"]
/* Handle the ESC/ENTER key with more specific element and cancel even bubbling for these actions to void bp-default's way of handling this */
jq('.ac-textarea textarea').keydown( function(e) {
element = e.target;

//if meta keys, don't do anything
if( e.ctrlKey == true || e.altKey == true || e.metaKey == true )
return;

var keyCode = (e.keyCode) ? e.keyCode : e.which;

//if ESC key was pressed
if ( keyCode == 27 ) {
jq(element).animate({'height':'13px'});//reset back to its original height

return false;

}
else if(keyCode==13){//if enter pressed
//jq(element).parent().next().click();//since we have not removed the submit button
ac_post_comment(element);
return false;

}

});//end of ESC/enter handling code
[/sourcecode]

As you can see in the above code, I have mentioned that writing the ac_post_comment function could be avoided by uncommenting the previous line(submit button clicking). The problem is the javascript in bp-default hides the reply box below the posted comment but we don't want that. So, you can either uncomment a line in global.js or use the code below.

[sourcecode language="javascript"]

/**post activity comment*/
//just a copy of bp-default activity comment posting code with slight modification to avoid hiding the forms
function ac_post_comment(target){
target=jq(target);

/* Activity comment posting */
if ( target.hasClass('ac-input') ) {
var form = target.parent().parent().parent();
var form_parent = form.parent();
var form_id = form.attr('id').split('-');

if ( !form_parent.hasClass('activity-comments') ) {
var tmp_id = form_parent.attr('id').split('-');
var comment_id = tmp_id[1];
} else {
var comment_id = form_id[2];
}

/* Hide any error messages */
jq( 'form#' + form.attr('id') + ' div.error').hide();
target.next('.loader').addClass('loading').end().prop('disabled', true);

jq.post( ajaxurl, {
action: 'new_activity_comment',
'cookie': encodeURIComponent(document.cookie),
'_wpnonce_new_activity_comment': jq("input#_wpnonce_new_activity_comment").val(),
'comment_id': comment_id,
'form_id': form_id[2],
'content': jq('form#' + form.attr('id') + ' textarea').val()
},
function(response)
{
target.next('.loader').removeClass('loading');

/* Check for errors and append if found. */
if ( response[0] + response[1] == '-1' ) {
form.append( response.substr( 2, response.length ) ).hide().fadeIn( 200 );
} else {
form.fadeOut( 200,
function() {
if ( 0 == form.parent().children('ul').length ) {
if ( form.parent().hasClass('activity-comments') )
form.parent().prepend('<ul></ul>');
else
form.parent().append('<ul></ul>');
}

form.parent().children('ul').append(response).hide().fadeIn( 200 );
form.children('textarea').val(");
form.parent().parent().addClass('has-comments');
}
);//form hiding
jq( 'form#' + form.attr('id') + ' textarea').val(");
target.height(20);
// form.removeClass('active');
form.fadeIn(200);

/* Increase the "Reply (X)" button count */
jq('li#activity-' + form_id[2] + ' a.acomment-reply span').html( Number( jq('li#activity-' + form_id[2] + ' a.acomment-reply span').html() ) + 1 );
}

jq(target).prop("disabled", false);
});

return false;
}
}

[/sourcecode]

Now, we have done everything and the code will work. The last thing we need to fix is clicking on the comment(x) link below the activity entry. By default, bp-default theme show the comment form for that activity and hides all other comment form. we need to stop it hiding other comment form. You can uncomment a line in global.js or just use the code below.

[sourcecode language="javascript"]

/* You can avoid the code blow if you want to change a line in global.js, if you don't, then this code does it for you*/
//the code below is taken from bp-default activity comment link clicking code, I have attached the evnt to more specific element and also remoded the form hiding code
jq('div.activity .acomment-reply').click( function(event) {
var target = jq(event.target);

var id = target.attr('id');
ids = id.split('-');

var a_id = ids[2]
var c_id = target.attr('href').substr( 10, target.attr('href').length );
var form = jq( '#ac-form-' + a_id );

form.css( 'display', 'none' );
form.removeClass('root');
//jq('.ac-form').hide();//you can just comment out this line in the global.js of bp-default and avoid this whole block of code

/* Hide any error messages */
form.children('div').each( function() {
if ( jq(this).hasClass( 'error' ) )
jq(this).hide();
});

if ( ids[1] != 'comment' ) {
jq('div.activity-comments li#acomment-' + c_id).append( form );
} else {
jq('li#activity-' + a_id + ' div.activity-comments').append( form );
}

if ( form.parent().hasClass( 'activity-comments' ) )
form.addClass('root');

form.slideDown( 200 );
jq.scrollTo( form, 500, { offset:-100, easing:'easeOutQuad' } );
jq('#ac-form-' + ids[2] + ' textarea').focus();

return false;

});

[/sourcecode]

That's it. You are ready to see your supercool facebook like activity commenting.

I have put the above code as a child theme of bp-default on github. If you want to take a look and see it in action, download it from here and active.

Github Repo:https://github.com/sbrajesh/fb-style-activity-commenting

My tutorial uses the reference of bp-default theme for BuddyPress 1.5 but you can modify it for any of the existing theme with some minor css/js changes if any.

Hope it helps some of you. Looking forward to hear your thoughts and feedback 🙂

51 Responses to Facebook Style Activity Commenting with BuddyPress

  • Hi Brajesh,

    Great work there, works great for bp-default,
    I did try to use it on both BP-Mag & Cosmic Buddy Pro but wouldn't work correctly,
    When it came to clicking "Enter" it just created a new line, I didn't test it long enough on them to get into it as i was busy on something else,
    But I'll get around to it at some point,
    So thanks again for some of your awesome work Brajesh 🙂

    Ben.

    • Hi Ben,
      Thank you for the comment.
      To make it work with bp-mag/cosmic buddy check the wp_enqueue_script tag, I have put a dependency on bp-dtheme-js as in array('jquery','dtheme-ajax-js'), Just change that with bp-mag's js handle.

      Hope that helps 🙂

  • Thanks Brajesh,
    But i still couldn't get it to work correctly, Think I'm missing something else,
    Doesn't help i have a head ache, I'll try again later once i get rid of this head ache.

    • Hi Ben,
      Please let me know If I can be of any help 🙂

      • Thanks Brajesh,
        Yeah that would be good if you can help, Only when you have time though,:)
        I've been customising Cosmic buddy pro so much and the "clicking enter" just isn't working for me.

        • Hi Ben,
          I will be happy to help you this weekend. I have been looking at the screenshots you posted a few weeks ago and the things look very promising 🙂

        • Thanks Brajesh,

          I've now fixed the CB pro theme gradients to work with Android & Apple devices & all Internet Explorer browsers,
          I had to use JavaScript for some fixes on Apple devices so i could use bp-chat, You'll most probably see the CSS changes at the weekend,
          This also includes the Buddybar, But as always everything looks better on Firefox & now Safari.

  • awesome trick @sbrajesh !! will definitely give this a shot… thank u very much for this.

  • Does it consolidate and then expand multiple comments? Give a comment count headline and other headline for likes, etc.?

    • Hi,
      Isn't that already part of BuddyPress activity stream for BP 1.5+, If there are more than 5 comments only last 5 is shown and a link to show all is given ? I hope you are referring to the same feature. Please correct me if I am wrong?

      • I must have missed that in my upgrade…Yep…I did. You're right 1.5 does that! thanks

      • Hi, Brajesh,

        I want to be able to use my comment section extensivly for my community because I don't want people to log into my admin panel. I am also not thrilled about topics or forums, so the only solution I came up for is actually using comment section. It does almost exactly what I want. The problem is that I can't find information on how to make it perfect. I have been doing my research and so far your post seems the most helpful. Please point me in the right direction on following questions. Thank you. I apologize if you have this info somewhere on your site, I just came across this topic and got very excited that decided to post all my questions immediately.

        Does this feature (displaying up to 5 commnets) hold true only for activity stream or pages also?

        Could you recommend me a solution on how to display less than 5 comments in the page comments? (Ideally, I want to display 1 or 0 comments and hide the rest under "Show all"

        I also hasn't been able to figure about how to insert a button like the one you have under your comments: "Notify me of followup comments via e-mail"

        Another problem is how to get rid of text "You may use these HTML tags…"

        And also I don't know how to change text of "Leave a Reply" to "Write a Post"

        • Well, here is a little update on my progress. Right after I wrote this post, I was able to find a couple of answers to my questions:

          In my theme's comment.php I passed the following data to comment_form function and it worked.

          "Write a Post", 'comment_notes_after' => ")); ?>

          It fixed these two issues:
          Another problem is how to get rid of text “You may use these HTML tags…”
          And also I don’t know how to change text of “Leave a Reply” to “Write a Post”

          Then I installed a plug in "Subscribe to Comments" which let me add "Notify…" check-box. The only problem with it is that I would hope that it would display above "Post Comment" button, but I am clueless as how to make it. I just don't know where to look for it. Maybe you could give me your advice. This is how it looks 20 Gift Ideas for Grandmothers

          And this question still remains unresolved: "Could you recommend me a solution on how to display less than 5 comments in the page comments? (Ideally, I want to display 1 or 0 comments and hide the rest under “Show all”

  • Hi Brajesh, I've just checked my implementation of BP 1.5 and there's no expandable comments in the activity stream as far as I can tell. Seems to function exactly as it did in 1.29.

    There was an old plugin that I played around with earlier this year, but which no longer works in later versions of BP. It would definitely be a worthwhile inclusion in this Fb-style plugin.

    • You're right, truncation of the activity feed comments is in BP 1.5 (the threshold is set at 8 comments).

  • Hi Brajesh,

    Here's the almost finished look 🙂

    • Wow! I initially could not even recognize it as cosmic buddy pro. Only looking after the content area it looks like Cosmic Buddy content area 🙂
      Awesome mods 🙂

  • Thanks Brajesh 🙂

  • Hi Brajesh,
    great tutorial, as always.
    should I try it on BP 1.2.10, or it is 100% incompatible?

    thanks.

    • Hi James,
      Thank you for the comment.
      I haven't tried it on bp 1.2.x, so unable to say anything about that. I hope it can be made to work with 1.2 with some minor changes.

  • Hi Brajesh and thank you again for your great work! About this script, there's a little problem with "Esc" function below comments. Sometimes, when a user press "Esc", it doesn't work. Ex: The blank space in the form (where comment can be written) doesn't collapse and it seems to happen when I'm in a profile or I do a refresh in the activity section. It works ever properly, instead, if I pass from a tab to another. A solution is possible?

    Thank you again

    • Another thing… i'm working with Frisco Theme

  • Can you please help me on this, I'm new to jquery and your plugin works fine but when I switch tabs to "My friends activity" or "My groups activity" the textarea autorezise no longer works.. I read about the livequery plugin but I don't have an idea how to make it work with your code.. any help?

    • Hi Sajok,
      sorry I could not help earlier.
      I hope you managed to get it working. Please do let me know if I can be of any help.

      Regards
      Brajesh

      • thanks, I'm new to jquery and I have managed to get it working with the livequery jquery plugin.. but I wonder if there is a better way..

  • @Sbrajesh, thanks for this great tutorial, the only problem i have is when you load more activity, any comment you post on that more activity will not work. any way to fix that?.

    Regards

    • Hi Abbey,
      is it still happening. Is it happening with the default theme or any other theme ?

  • Hi Brajesh,

    I love the thought of this, and have tried to implement the code on my very first BP site, but no luck so far, as to get it working.
    I suspect it's because I have to change something here:

    wp_enqueue_script("bpfb-comment-js", get_stylesheet_directory_uri()."/_inc/comment.js",array('jquery','dtheme-ajax-js'));

    I use the Custom Community Pro theme for my site (http://custom-community-pro.themekraft.com/)
    I'm not sure where I would find the right names for the code above. I understand that it is theme-dependant?

    Sorry for the noob questions, but although I have had WordPress sites for some years now, this is my first BuddyPress site, and I am totally lost concerning javascript/jquery and so on. I tend to lean on plugins and generally tweaking the look to my likings via css, but I can't find any plugin for this, so had to try to implement it myself.

    I have copied your files from github, but it simply doesn't work for me.
    You can see my activity stream here: http://soelver.dk/sphynxforum/activity/

    Any hints for me, to guide me in the right direction?

    Best regards,

    Anita

  • Your activity comment notification plugin doesn't seem to work with the comment box. If someone replies by using the new comment box it doesn't notify you.

    • (By that I mean: I created the Facebook style activity comment box and disabled multilevel commenting. But your comment notification plugin only seems to notify people if they reply to a comment, not to the content itself.)

  • this has stopped working in the newer buddypress, anyway to fix it?

    regards

    • Hi Abbey,
      sorry for the late reply.
      Do you mean BuddyPress 1.7 beta or BuddyPress 1.6.4?

  • thanks @sbrajesh, for your reply, it has stopped working since 1.6.

    if you type a comment and hit enter, the comment form just keep enlarging, and enter will post nothing.

    regards

  • @sbrajesh, anyway suggestion on how to fix this problem please?

    thanks

  • Works perfectly! Thanks @sbrajesh

  • Hi guys…i have had this plugin from day 1 and it has worked fine until now….what have i done lately? well…i have updated my wp/bp & most importantly my custom community theme.
    What Exactly is the problem??? Well!!!:
    When my member post a comment from the “MY STREAM” tab it works fine but, when another member or the same member want to reply to his or her posts is simply does not post….it show a “1 comment” but there is not an actual post attached to the comment….i am getting ripped into pieces on my social network ppllleaaaseeeee someone help me figure out what is going wrong with this plugin.
    BTW THE THE BP AUTO-LOADER IS THE BOMB!!!! WORKS BEAUTIFULY.

  • Hey Brajesh,

    The CSS seems to be working but for some reason or another my bpress installation doesn't seem to want to use comments.js. Any ideas?

    Thanks.

    • -I changed the paths to my scripts as suggested in the guide in Step 1, fixed!-

      I had another question, however. I was wondering how you might go about adding disappearing text; i.e. "Write a comment…" as seen on facebook?

  • Unfortunately it's not working with new Buddypress 🙁 Any help would be so very much appreciated.

  • rob #

    Hi Brajesh,

    Nice plugin!

    One quick question, the amount of comments that are on displayed by default is 5. How do I change it to 3?

    Thanks
    Rob

    • Hi Rob,
      Please look into your buddypress.js
      You will see a function named 'bp_legacy_theme_hide_comments'. The number is hard coded there. You can change it if you want.