While using AJAX to retrieve JSON data containing information on the next steps, I am implementing a CSS class hide/show to toggle images/wrapper and loading .png image.
However, even after toggling show/hide on the image, updating the image src, and adding/removing CSS classes on the new image, there are instances where the old picture briefly displays before transitioning to the new image src.
I attempted to introduce a 150-millisecond delay at the end, but the issue persisted.
function newImage(voteValue, imgValue, checked) {
if (checked == "") {
var innerVotingWrapper = document.getElementById('innerVotingWrapper');
innerVotingWrapper.innerHTML = "You must select a category";
console.log(checked);
} else {
var loadingWrapper = document.getElementById('loadingWrapper');
var imgSrc = document.getElementById('imgSrc');
var globalRating = document.getElementById('globalRating');
globalRating.classList.add("hide");
globalRating.classList.remove("show");
imgSrc.classList.add("hide");
imgSrc.classList.remove("show");
loadingWrapper.classList.add("show");
loadingWrapper.classList.remove("hide");
var http = new XMLHttpRequest();
var url = "pages/newImage.php";
var params = "voteValue=" + voteValue + "&imgValue=" + imgValue + "&checked=" + checked;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function () {
if (http.readyState === 4 && http.status === 200) {
var jsonData = JSON.parse(this.responseText);
setTimeout(func, 1000);
function func() {
console.log(this.responseText);
console.log(jsonData.checked);
loadingWrapper.classList.add("hide");
loadingWrapper.classList.remove("show");
if (jsonData.imgSrc) {
imgSrc.src = jsonData.imgSrc;
}
if (jsonData.id) {
var imgValue = document.getElementById('imgValue');
imgValue.value = jsonData.id;
}
if (jsonData.empty) {
console.log('No more images');
var innerVotingWrapper = document.getElementById('innerVotingWrapper');
innerVotingWrapper.innerHTML = "You have voted on all images, come back in 24 hours";
}
function showImg() {
globalRating.classList.add("show");
globalRating.classList.remove("hide");
imgSrc.classList.add("show");
imgSrc.classList.remove("hide");
}
setTimeout(showImg, 150);
}
}
};
http.send(params);
}
}