inject spinner during the call and verify status post-call

How can I make the loading icon display during the save function call and then switch to the check mark icon after the function resolves instead of mocking it on a timeout?

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);
}

View JSFiddle Demo

Answer №1

When the save button is clicked, the following code will display loading and done statuses. You have the option to replace the text with icons or images as needed.

function save() {
  
  let save = document.getElementById("save");
  
  save.innerHTML = 'Loading...'; // Change this to your desired loading indicator

  new Promise((resolve, reject) => {
    setTimeout( function() {
      resolve("Success!")
    }, 2500) 
  }).then(function(){
  
    save.innerHTML = 'Done'; // Change this to your desired completed status indicator
    
  }) 
}
<button id="save" onclick="save()">
Hello
</button>

Answer №2

If you're looking to execute asynchronous operations in steps, you can achieve this by utilizing the then function.

Furthermore, is it necessary to dynamically create an img element for icons? The Button element can encompass child nodes in HTML.

The code snippet below is derived from your own:

http://jsfiddle.net/oqs9wdh0/

Upon clicking the button, it will display a spinner and success icon a second later.

let el = document.querySelector('button')
let check = el.querySelector('.icon.check')
let spinner = el.querySelector('.icon.spin')
  
function save() {
    // display 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) {
  // toggle visibility
  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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The email validation UI dialog is failing to display any dialog

<html> <head> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"& ...

Summing up numbers within a hierarchical table using jQuery

There are two tables, each with their own unique ID as shown below: <table id="cvo"> <tr id="1"> <td>C</td> </tr> <tr id="2"> <td>C</td> </tr> <tr id="3"> <td>O</ ...

Mongoose search operation coming up with a blank array

Whenever I utilize $search in mongoose, it returns an empty array. Data Model const mongoose = require('mongoose'); const studentSchema = new mongoose.Schema({ name: { type: String }, }); studentSchema.index({ name: 'text' }); con ...

Unable to set the height for ul/div elements

I'm struggling to make my navbar appear when I click the "menu button". The div seems to be present in the code, but with a height of 0. Here's the relevant section of the code causing the issue. Any suggestions on how I can resolve this? var ...

Discover the security vulnerabilities in Node.js when using VS Code with FREECODECAMP's React app

As a beginner in using VS code, I attempted to work on a project for FREECODECAMP. This project involved creating a random quote machine, marking my first time coding a react project. While following a YouTube tutorial and making progress towards functiona ...

What is the most popular method for namespacing AngularJS modules?

I am new to AngularJS and currently exploring different ways to namespace modules in my application. One challenge I face is the need to integrate my Angular app into a designated placeholder div within a third-party website (which may also use Angular), ...

Does the TS keyof typeof <Object> rule prohibit the assignment of object.keys(<Object>)?

I'm having trouble understanding the issue with this code snippet. Here is the piece of code in question: export type SportsTypes = keyof typeof SportsIcons export const sports: SportsTypes[] = Object.keys(SportsIcons); The problem arises when I at ...

Learn how to generate a DataTable in C# by parsing multiple nested JSON Objects efficiently

Whenever I receive dynamic JSON data, it could be a JSON array, a simple JSON object, or nested JSON objects. I am attempting to deserialize and convert the JSON object/array into a DataTable for further processing using Newtonsoft.Json. Here is my curre ...

transfer the form file to php using ajax requests

I am trying to send a file to PHP using AJAX. Below is the code I have written, but when I run it, I get an error saying "Undefined index: thefile". Can anyone help me identify the problem? HTML function sendData(url){ var xmlHttp = new XMLHttpRequ ...

Inability to successfully upload batch data within specified criteria using a keyword and conditional statement

My goal is to batch the data, using "Repair" as a separator for the data. Splitting criteria = Repair Copper limit = 2.5 [ {"engineSN":"20","timeRun":"30","Cu":"2"}, {"engineSN": ...

A comprehensive guide on creating a package that combines an href link with an <li> element

I am currently using the <li> tag to display href links. The issue I am facing is that when I click on the 'box,' it does not directly link to another page. Instead, I have to click on the href link for it to redirect to another page. Is th ...

Incorporating a scrollbar when a div exceeds the bottom of the viewport

I am encountering an issue on my webpage with a <div> that contains a <table> with rows of varying heights: <html> <head></head> <body> <div> <table> <tr>... <tr>... ... </ ...

Get rid of numerous div elements in a React.js application with the help of a Remove button

I need help figuring out how to efficiently remove the multiple div's that are generated using the add button. I am struggling to grasp how to pass the parent div's id into the delete method from the child div. Additionally, I'm wondering if ...

Issue with Hover Behavior in Bootstrap 5 Navbar Dropdown

While developing a website using Bootstrap 5, I encountered an issue with the navbar dropdown not opening on hover despite attempting to add custom CSS. Strangely, the CSS code worked perfectly in isolation when I tested it in a code snippet, but failed to ...

Developing uniform resource locators with jQuery

As I work on developing my webapp, I have made use of the tag in my JSPs to ensure that all links within the application - whether they lead to pages or resources like images and CSS - always stem from the root directory rather than being relative to the ...

No search results found for Mongoose text search query

Despite using Mongoose 5.7.8 for my app, the text search feature is not yielding any results. Below is a schema/model example: import mongoose, { Document, Schema } from 'mongoose'; import { Moment } from 'moment'; import { IUser } fr ...

Should you choose a pre-built CSS framework or create your own from scratch?

Have you come across a framework that meets your project needs with just a few tweaks, or have you forged your own path along the way? What advice do you have for someone facing this decision and focusing on priorities like: Implementing a CSS reset Refi ...

Initiate the video tag playback by using jquery.play() function

Is there a way to make the video start playing as soon as the overlaying absolute div has faded out? I've tried using javascript and autoplay, but it doesn't seem to work without controls enabled. Any suggestions? Check out the HTML code below: ...

Angular: Failure in receiving EventEmitter's event with .subscribe method

My current challenge involves handling an event coming from NgLoopDirective within the method EV of NgDNDirective. I am attempting to achieve this by passing the EventEmitter object by reference and then calling .subscribe() as shown in the code snippet be ...

Angular is not programmed to automatically reflect updates made to my string array

let signalRServerEndPoint = 'https://localhost:44338'; this.connection = $.hubConnection(signalRServerEndPoint); this.proxy = this.connection.createHubProxy('MessagesHub'); this.proxy.on("ReceiveMessage", (message) => { ...