jQuery AJAX: How to append a “SAVED” message and make it disappear after a second
Question
this is probably really simple for a jQuery expert.
I have <div id="form23"><form><textarea>blahblah</textarea><input type="button" value="save" onClick="saveCaption(23)"></form></div>
I want a SAVED message appear and disappear. But I DO NOT want to make the form or its elements disappear.
I have a AJAX call that is like the following.
function saveCaption(id) {
var queryString = $('#form'+id).formSerialize();
$.ajax({
type: "POST",
url: "includes/ajax.php?request=saveCaption",
data: queryString,
success: function(response) {
$('#form'+id).append(response)
}
});
return false;
}
I was wondering.. I can append the response. But is there a way to fade it out right away after a second. Right now, it just keeps repeating and adding to the last append. I would like it to appear and disappear right after using fadeOut.
UPDATE: I did this based on theIV and RaYell's response. It works.. but is it elegant?
function saveCaption(id) {
var queryString = $('#form'+id).formSerialize();
$.ajax({
type: "POST",
url: "includes/ajax.php?request=saveCaption",
data: queryString,
success: function(response) {
$('#form'+id).append('<div id="message">'+response+'</div>');
setTimeout(function () {
$('#message').fadeOut(function(){
$(this).remove();
});
}, 1000);
}
});
return false;
}
Solution
I think you'll want to do a combination of RaYell's answer above but use a remove in the fadeOut callback, or else it will continue to append to the previous append—at least, I think it will do that based on the way you phrased your question. Something like this could work:
setTimeout(function () {
$('selector').fadeOut(function(){
$(this).remove();
});
}, 1000);
OTHER TIPS
After you append your message add this (inside success callback):
setTimeout(function () {
$('selector').fadeOut();
}, 1000);
Replace selector with something that will actually match your message.