Reputation: 518
I am trying to add a spinner icon during the my function call and then after the call to return a check mark image:
My issue is that I m not updating the loading or check icon according to the callback but instead i m mocking it on a timeout. How can I display the loading icon during the save function and then check after the function resolves?
function save() {
successMessage()
new Promise((resolve, reject) => {
setTimeout( function() {
resolve("Success!")
}, 250)
})
}
function createIcon(src, title) {
let img = document.createElement('img');
img.src = src;
img.className = 'icon'
img.style.display = 'none'
if (title != null) {
img.title = title
img.alt = title
}
if (src.indexOf('spinner') > 0) img.classList.add('spin')
return img;
}
function successMessage() {
let el = document.querySelector('button')
let check = this.createIcon("check.svg", "Updated")
let spinner = this.createIcon("spinner.svg", "Updating...")
if (el.childNodes.length === 1) {
el.appendChild(spinner)
el.appendChild(check)
}
check.style.display = 'none'
spinner.style.display = 'initial'
setTimeout(function() {
spinner.style.display = 'none'
check.style.display = 'initial'
}, 500);
}
Upvotes: 0
Views: 527
Reputation: 324
If you want an asynchronous operation steps, it can be returned and called by using then
.
And, Does it need to create img element for icons dynamically? Button
element can be contained child nodes as HTML.
The following code are forked from yours:
you clicked button, then it shows spinner and success icon in a second later.
let el = document.querySelector('button')
let check = el.querySelector('.icon.check')
let spinner = el.querySelector('.icon.spin')
function save() {
// show spinner
check.style.display = 'none'
spinner.style.display = 'initial'
// success after a second
return new Promise((resolve, reject) => {
setTimeout(function() {
resolve("Success!")
}, 1000)
})
}
function successMessage(result) {
// hide and show
spinner.style.display = 'none'
check.style.display = 'initial'
alert(result)
}
button > img.icon {
display: none;
}
<button onclick="save().then(successMessage)">
Hello
<img src="check.svg" class="icon check" alt="Successfully updated">
<img src="spinner.svg" class="icon spin" alt="Updating...">
</button>
Upvotes: 1
Reputation: 1003
The following will show statuses of loading and done when the save button is click. You can replace the word to icon or images accordingly.
function save() {
let save = document.getElementById("save");
save.innerHTML = 'Loading...'; // to replace anything you want when loading
new Promise((resolve, reject) => {
setTimeout( function() {
resolve("Success!")
}, 2500)
}).then(function(){
save.innerHTML = 'Done'; // to replace anything you want to show status completed
})
}
<button id="save" onclick="save()">
Hello
</button>
Upvotes: 2