I'm trying to replace an element using fade animation with only javascript. I figure it needs to use Promise and async/await mechanism so I tried to write the code below. the fadeOut process works fine, but somehow the 2nd element won't appear.. what am I doing wrong?
here's my code:
const main = document.querySelector('#main');
const el0 = document.querySelector('.x');
const str = '<div class="asd1">Hello</div>'; // generated from fetch result
main.insertAdjacentHTML('beforeend', str);
const el1 = document.querySelector('.asd1');
(async() => {
await fadeOut(el0, 1000);
await fadeIn(el1, 1000);
})();
function fadeIn(elem, ms) {
return new Promise((resolve, reject) => {
if (!elem)
return;
elem.style.opacity = 0;
elem.style.filter = "alpha(opacity=0)";
elem.style.display = "inline-block";
elem.style.visibility = "visible";
if (ms) {
var opacity = 0;
var timer = setInterval(function() {
opacity += 50 / ms;
if (opacity >= 1) {
clearInterval(timer);
opacity = 1;
}
elem.style.opacity = opacity;
elem.style.filter = "alpha(opacity=" + opacity * 100 + ")";
}, 50);
} else {
elem.style.opacity = 1;
elem.style.filter = "alpha(opacity=1)";
}
resolve(elem);
});
}
function fadeOut(elem, ms) {
return new Promise((resolve, reject) => {
if (!elem)
return;
if (ms) {
var opacity = 1;
var timer = setInterval(function() {
opacity -= 50 / ms;
if (opacity <= 0) {
clearInterval(timer);
opacity = 0;
elem.style.display = "none";
elem.style.visibility = "hidden";
}
elem.style.opacity = opacity;
elem.style.filter = "alpha(opacity=" + opacity * 100 + ")";
}, 50);
} else {
elem.style.opacity = 0;
elem.style.filter = "alpha(opacity=0)";
elem.style.display = "none";
elem.style.visibility = "hidden";
}
});
}
.asd1 {
width: 100px;
height: 100px;
background-color: red;
opacity: 0;
}
.x {
width: 50px;
height: 50px;
background-color: purple;
}
<div id="main">
<div class="x">
blah
</div>
</div>
I finally remake the whole function into a simpler one like this and it works
let elem = document.querySelector('.asd');
let elem2 = document.querySelector('.asd2');
let ms = 2000;
let intrvl = 20;
const action = fadeOut(elem, ms, intrvl);
action.then(response => {
console.log('res', response);
ms = 200;
intrvl = 20;
return fadeIn(elem2, ms, intrvl);
}).then(response => {
console.log('res2', response);
});
function fadeIn(elem, ms, intrvl) {
return new Promise((resolve) => {
let opacity = 0;
setInterval(() => {
opacity += intrvl/ms;
elem.style.opacity = opacity;
if (opacity >=1) {
resolve('selesai fade in');
}
}, intrvl);
});
}
function fadeOut(elem, ms, intrvl) {
return new Promise(resolve => {
let opacity = 1;
setInterval(() => {
opacity -= intrvl/ms;
elem.style.opacity = opacity;
if (opacity < 0) {
elem.style.display = 'none';
resolve('selesai fade out');
}
}, intrvl);
});
}
.asd {
opacity: 1;
}
.asd2 {
opacity: 0;
}
<div class="asd">Hello World!</div>
<div class="asd2">New Item!</div>