Skip to content

Instantly share code, notes, and snippets.

@pommiegranit
Last active August 29, 2015 13:56
Show Gist options
  • Save pommiegranit/8969845 to your computer and use it in GitHub Desktop.
Save pommiegranit/8969845 to your computer and use it in GitHub Desktop.
Paragraph Commenting Snippets
// this function courtesu of Werx Limited
// http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/
String.prototype.hashCode = function(){
var hash = 0;
if (this.length == 0) return hash;
for (i = 0; i < this.length; i++) {
char = this.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
window.set_up_para_comments = function() {
if ( current_para_id ) {
$( 'div.inline-comments-container .inline-comments-content' ).hide();
$( 'div.comment-para-id-' + current_para_id ).show();
$( 'div.inline-comments-content-comment-fields' ).show();
return;
}
$( 'div.inline-comments-content-comment-fields' ).hide();
// set up paragraph ids
// WARNING! if text changes then hashCode will change and comments will be orphaned
$('p').each( function( index ) {
// generate hashcode
var para_id = $( this ).text().hashCode();
// add the hashcode as an id
$( this ).addClass('para-id-' + para_id );
// also store the para_id on the p so that we can use it later
$( this ).attr( 'data-para-id' , para_id );
// get comments
var comments = $( 'div.comment-para-id-' + para_id );
// hide them
comments.hide();
// remove the orphan-comment class (only those comments without a matching p will be left)
comments.removeClass('orphan-comment');
// add the number of comments to the link
$( this ).append('<span class="p-comment-count"><a href="#" class="toggle_comments">' + comments.length + '</a></span>');
});
var orphans = $('div.orphan-comment');
if ( orphans ) {
$('<div class="orphan-comments-container"><p>These are orphan comments - the paragraph they were attached to has either been edited or deleted.</p></div>').insertAfter('div[name="comments"]');
$('div.orphan-comments-container').append( orphans );
}
}
$( document ).on('click', '.toggle_comments', function( event ){
event.preventDefault();
var container = $('div[name="comments"]');
if ( container.css('z-index') == '999999' ) {
container.css('z-index' , '-999999');
return;
}
// get the position of the clicked comment count
var position = $( this ).position();
//get the grandparent
var para = $( this ).parent().parent();
// get the para_id
current_para_id = para.attr('data-para-id');
// show only this paragraphs comments plus the new comment form
$( 'div.inline-comments-container .inline-comments-content' ).hide();
$( 'div.comment-para-id-' + current_para_id ).show();
$( 'div.inline-comments-content-comment-fields' ).show();
// style the comment box
container.css('z-index' , '999999' );
container.css('top' , position.top + 30 );
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment