In this post I'm going to show you how to create a visual effect while publishing or deleting your blog comments using jQuery. Since I can't use a database on this example, I'll explain later how to actually publish or delete your blog comments using jQuery's AJAX methods. For now let's focus on the visual effect we want to achieve. Let's say that we have a sequence of comments, each one with a "Publish" and "Delete" button at the bottom of it. When we click on each button, we want the comment to disappear and be replaced with a different message. Here's the jQuery code:
$(document).ready(function() { $('a.publish').each(function() { var $a = $(this), published = '<p class="published">Comment published</p>'; $a.click(function(e) { $a.parents('blockquote.comment').fadeOut('slow', function() {$(this).replaceWith(published)}); e.preventDefault(); }); }); $('a.delete').each(function() { var $a = $(this), removed = '<p class="removed">Comment removed</p>'; $a.click(function(e) { $a.parents('blockquote.comment').fadeOut('slow', function() {$(this).replaceWith(removed)}); e.preventDefault(); }); }); });
When we click on a link, jQuery selects the top parent element of each link (that is, the comment block itself) and make it disappear using the fadeOut()
method. As you can see, we have attached a callback function to this method so that when the element disappear it's actually replaced by the proper message.
Using AJAX
To use AJAX, you basically need:
- a server-side script that processes your requests
- some content returned by the aforementioned script
If you use PHP, you could write something like this:
header('Content-Type: text/plain'); $action = $_GET['action']; switch($action) { case 'delete-comment': // delete comment on the database echo '<p class="removed">Comment removed</p>'; break; case 'publish-comment': // insert your comment on the database echo '<p class="published">Comment published</p>'; break; default: break; }
Then you had to modify the default actions of each link:
$('a.publish').each(function() { var $a = $(this); $a.click(function(e) { $.ajax({ type: 'GET', url: 'process.php', data: 'action=publish-comment', success: function(message) { $a.parents('blockquote.comment').fadeOut('slow', function() {$(this).replaceWith(message)}); } }); e.preventDefault(); }); });
You can do the same for the "Delete" link.
thanks for the script !
i really need it...