Reputation: 5
I have a fairly simple jQuery snippet that fades out an element then loads an external PHP page via AJAX after a button is clicked, and I'm trying to do the same thing using Javascript, so I can avoid using jQuery at all.
jQuery:
$(document).on("click", "#button", function () {
$("#image").fadeOut(580, function () {
$("#image-wrapper").load("loader.php");
});
return false;
});
Javascript:
document.getElementById("button").addEventListener("click", function () {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 300) {
document.getElementById("image").classList.add("fade--out");
document.getElementById("image-wrapper").innerHTML = xhr.responseText;
console.log("Success");
} else {
console.log('Error');
}
};
xhr.open('GET', 'loader.php');
xhr.send();
});
And some CSS:
.fade--out {
opacity: 0;
}
#image {
transition: opacity 480ms ease 0s;
}
So far I have written that but I can only get the XMLHttpRequest
to work ok but I can't seem to get the image
element to fade out before loading the PHP file. How can I get the image
div to fade out then load the PHP file inside the imaga-wrapper
div?
Upvotes: 0
Views: 131
Reputation: 65855
See comments:
document.addEventListener("click", function (evt) {
// Because of event delegation, we need to check to see
// if the source of the event was the button
if(evt.target.id === "button"){
// Add a class to the image that changes the opacity to fully
// transparent, but because of the default image styling, a
// CSS transition will do that over the course of 480 milliseconds.
document.getElementById("image").classList.add("fade--out");
// Once that is done, call the supplied function
requestAnimationFrame(function(){
// AJAX Call here
});
}
});
.fade--out {
opacity: 0;
}
#image {
transition: opacity 480ms ease 0s;
}
Upvotes: 1