At the moment I have the following jQuery/Ajax in order to load the comments when a user clicks on a div:
function showComments(post_id) {
$("#comment-"+post_id).toggle();
$.ajax({
dataType: 'html',
cache: false,
url: 'ajax.php',
type: 'POST',
data: {comments: post_id}
}).done(function(html) {
$('#comment-'+post_id).html(html)
});
}
This all works fine, as the default div has the spinner in it, which is shown until the content has loaded. However, if a user clicks on it again to hide it, then clicks to show again the spinner doesn't appear because the content isn't being reset obviously. So I tried to use .toggles mouse event handler:
function showComments(post_id) {
$("#comment-"+post_id).toggle(function() {
$('#comment-'+post_id).show();
$.ajax({
dataType: 'html',
cache: false,
url: 'ajax.php',
type: 'POST',
data: {comments: post_id}
}).done(function(html) {
$('#comment-'+post_id).html(html)
});
}, function() {
$('#comment-'+post_id).hide();
$('#comment-'+post_id).html('<img src="/loader.gif" />')
});
}
However, this time, nothing works, the div doesn't show, or hide, and the Ajax isn't called. Any ideas what I've perhaps done wrong?
EDIT:
Here's the HTML/PHP:
<div class="comments right" title="Click to view comments" onclick="showComments('.$post['id'].')">'.$post['comments_cache'].'</div>
<div style="display:none" id="comment-'.$post['id'].'" class="top-15"><img src="/loader.gif" /></div>
There's nothing wrong with the above, it works fine with the first function I showed you.
Fixed it by doing:
function showComments(post_id) {
if ($('#comment-'+post_id).html().length > 0) {
$('#comment-'+post_id).empty().hide();
} else {
$('#comment-'+post_id).html('<img src="loader.gif" />').show();
$.ajax({
dataType: 'html',
cache: false,
url: 'ajax.php',
type: 'POST',
data: {comments: post_id}
}).done(function(html) {
$('#comment-'+post_id).html(html)
});
}
}
You could use the beforeSend
property of jQuery, and add a class 'open'
to the div once its open to keep track of the display.
function showComments(post_id) {
$("#comment-" + post_id).click(function () {
if (!$(this).hasClass('open')) {
$.ajax({
dataType: 'html',
cache: false,
beforeSend: function () {
$(this).show().addClass('open');
},
url: 'ajax.php',
type: 'POST',
data: {
comments: post_id
},
success: function (html) {
$(this).html(html);
}
});
} else {
$(this).hide().html('<img src="/loader.gif" />').removeClass('open');
}
});
}