$.fn.CommentEditor = function(options) { var OPT; OPT = $.extend({ url: "https://www.startbusinessinfrance.com/?ACT=71", comment_body: '.comment_body', showEditor: '.edit_link', hideEditor: '.cancel_edit', saveComment: '.submit_edit', closeComment: '.mod_link' }, options); var view_elements = [OPT.comment_body, OPT.showEditor, OPT.closeComment].join(','), edit_elements = '.editCommentBox', csrf_token = '2529f7866b62cf71677f2efefff450eab4572a2b'; return this.each(function() { var id = this.id.replace('comment_', ''), parent = $(this); parent.find(OPT.showEditor).click(function(e) { e.preventDefault(); showEditor(id); }); parent.find(OPT.hideEditor).click(function(e) { e.preventDefault(); hideEditor(id); }); parent.find(OPT.saveComment).click(function(e) { e.preventDefault(); saveComment(id); }); parent.find(OPT.closeComment).click(function(e) { e.preventDefault(); closeComment(id); }); }); function showEditor(id) { $("#comment_"+id) .find(view_elements).hide().end() .find(edit_elements).show().end(); } function hideEditor(id) { $("#comment_"+id) .find(view_elements).show().end() .find(edit_elements).hide(); } function closeComment(id) { var data = {status: "close", comment_id: id, csrf_token: csrf_token}; $.post(OPT.url, data, function (res) { if (res.error) { return $.error('Could not moderate comment.'); } $('#comment_' + id).hide(); }); } function saveComment(id) { var content = $("#comment_"+id).find('.editCommentBox'+' textarea').val(), data = {comment: content, comment_id: id, csrf_token: csrf_token}; $.post(OPT.url, data, function (res) { if (res.error) { hideEditor(id); return $.error('Could not save comment.'); } $("#comment_"+id).find('.comment_body').html(res.comment); hideEditor(id); }); } }; $(function() { $('.comment').CommentEditor(); });