jQuery AJAX "Loading..." image
by Nikola Mihin
HTML
<img id="loading" src="https://lh4.googleusercontent.com/XyTAwN2xpicPUqt7HXvCUle0PnPZeurz0l-i4RneP-Px6lKGchqF4jJzLuvNoBGrPMZESt4BUK0" alt="Loading..." />
<div class="photo-library">
<div class="photo-container">
<div class="photo-inner">
<img id="photo_1" class="photo" src="" alt="Test image 1" />
</div>
<div class="photo-buttons">
<button class="delete">Delete</button>
</div>
</div>
<div class="photo-container">
<div class="photo-inner">
<img id="photo_2" class="photo" src="" alt="Test image 2" />
</div>
<div class="photo-buttons">
<button class="delete">Delete</button>
</div>
</div>
<div class="photo-container">
<div class="photo-inner">
<img id="photo_3" class="photo" src="" alt="Test image 3" />
</div>
<div class="photo-buttons">
<button class="delete">Delete</button>
</div>
</div>
</div>
CSS
img#loading {
display:none;
position:absolute;
z-index:100;
}
div.photo-container {
float:left;
margin:10px;
}
div.photo-inner img {
height:100px;
width:150px;
}
div.photo-buttons {
text-align:center;
}
JavaScript
var $loading;
$(document).ready(function () {
$loading = $("img#loading");
$(".photo-library").on("click", "button.delete", function () {
if (confirm("Are you sure you want to delete this photo?")) {
var $container = $(this).parents(".photo-container");
var $photo = $container.find("img.photo");
var photoID = $photo.attr("id");
var fadeOut = $container.fadeOut(5000).promise();
showLoading($photo);
$.ajax({
type: "POST",
url: "/photos/ajax_delete/",
data: "id=" + photoID,
cache: false,
complete: function() {
$.when(fadeOut).done(function() {
hideLoading();
$container.remove();
});
console.log("fdmfdfnd")
}
});
}
});
});
function showLoading($object) {
var objPos = $object.offset();
var xCentre = objPos.left + ($object.width() / 2);
var yCentre = objPos.top + ($object.height() / 2);
$loading.offset( { left: xCentre, bottom: yCentre } ).show();
}
function hideLoading() {
$loading.hide();
}