What is the reason behind my difficulty in opening my dialog box modally using JavaScript?

I am looking to keep a dialog open while data is being fetched from the server. Here is the code I have written:

(async()=>{
    document.getElementById("dialog").showModal();
    if(condition1 is true){
        await server_call1();
    }
    if(condition2 is true){
        await server_call2();
    }
    if(condition3 is true){
        await server_call3();
    }
    document.getElementById("dialog").close();
})();

The server_call() functions are all independent of each other. When I run this code, I keep getting an error in my console:

Uncaught (in promise) DOMException: Failed to execute 'showModal' on 'HTMLDialogElement': The element already has an 'open' attribute, and therefore cannot be opened modally.

Can someone help me resolve this issue? Thank you.

EDIT: Here is my html:

<dialog id="dialog">
  <p style="font-family: cursive;">Fetching results, please wait.. </p>
</dialog>

Answer №1

I've found that by adding a close call before every open call, such as:

dialog.close();
dialog.showModal();

I believe it's odd to throw an exception for attempting to open the dialog twice.

Answer №2

According to the documentation provided by mdn regarding HTMLDialogElement.showModal()

https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/showModal

When attempting to open a dialog that is already open (i.e., when the open attribute is already set on the element), an InvalidStateError DOMException will be thrown.

See below for your code executed in a live snippet:

async function sleep(time) {
  return new Promise((resolve) => setTimeout(resolve, time));
}

async function server_call(){
  await sleep(500);
}

(async()=>{
  document.getElementById("dialog").showModal();    
  await server_call();
  await server_call();
  await server_call();
  document.getElementById("dialog").close();
})();
<dialog id="dialog">
  <p style="font-family: cursive;">Fetching results, please wait 2 seconds.. </p>
</dialog>

Answer №3

I encountered this issue when I solely developed a dialog using JS.

To resolve it, I inserted the newly constructed dialog into the DOM.

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

Is there a way to use an Angular $watch to determine the specific changes made to $scope.value?

I am monitoring a variable called $scope.value with a watch in my code. There are two ways in which the value can be updated: The first is by updating it from the controller, such as through any services. The second way is that any input event can also ...

karma - Plugin not located

Attempting to run JS test cases using karma, but consistently receiving a plugin not found error. Oddly enough, the same configuration file works perfectly for one of my co-workers. Below are the logs: $ karma start karma.conf.js 04 10 2016 17:51:24.755 ...

Update your content dynamically by refreshing it with JQuery/AJAX following the usage of an MVC partial view

Implementing the following JQuery/AJAX function involves calling a partial view when a selection is made in a combobox labeled "ReportedIssue" that resides within the same partial view. The div containing the table is named "tableContent". <script type ...

Strategies for organizing your week with a calendar

Hello, I am working on creating a weekly calendar using PHP and I want to add events to the calendar like in this example. However, I am unsure how to display the events in the calendar at the correct time of day. Here is the code snippet I am currently u ...

Converting a text file to JSON format using Adobe Acrobat: A tutorial on proper referencing

I am facing an issue with converting a string from a file attached to my PDF (JSONTEST.txt) into JSON format so that I can reference it using obj[key]. Despite trying to use eval(), I encounter the following error every time: SyntaxError: missing ; before ...

JQuery and PHP: Saving a rearranged set of divs in a form

Although I've searched for similar questions, none seem to address my specific issue. My problem involves a form with divs generated from a JSON array saved in a separate file. To style the form, I'm using Bootstrap and implementing JQueryUI&apo ...

The HTML generated by Selenium using Javascript is still missing some elements, despite accessing the document.body.innerHTML

Attempting to retrieve the HTML from a webpage that undergoes modification by JavaScript post-loading. Followed directions in this guide, executing the command below in my Python script after initial page load: html = browser.execute_script("return docume ...

Configuring Access-Control-Allow-Origin does not function properly in AJAX/Node.js interactions

I'm constantly encountering the same issue repeatedly: XMLHttpRequest cannot load http://localhost:3000/form. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefor ...

What is the best location to specify Access-Control-Allow-Origin or Origin in JavaScript?

After researching, I found out that I need to set my Access-Control-Allow-Origin or Origin tags. But the question is: where do I actually add these? The suggestions were to use them in the header section. I couldn't find any detailed explanation on t ...

How can I conditionally disable a button in Vue.js using an if statement?

Can someone help me figure out why all my buttons are getting disabled when I only want one to be disabled? Here is the code where I created a counter with vue.js: <body> <div id="app"> <button @click="co ...

Different option for animated side slider based on location

Whenever I click on this div, it slides out smoothly. Check out these images to get a visual of what I am aiming for: This is how the Div looks when collapsed by default https://i.stack.imgur.com/zJIsA.png Once slid out, the Div looks like this (highlig ...

Best practices for timeout in HTTP long polling

As an avid user of Javascript AJAX and long-polling, I am constantly seeking the best value for server response timeout. Despite scouring numerous documents, a detailed explanation for timeout continues to elude me. Some suggest 20 seconds, while others ...

There seems to be an issue with the functionality of Array.filter when trying to use it with arrays

I am facing an issue with filtering branchId from an Array. Here is the code snippet and steps I have taken. const [branchID,setBranchID]=React.useState([]); const tempTwo=[ { branchId: "61b25e0ae177d62ce4cb3b47", bra ...

The interaction between jQuery and Rails through ajax calls

Attempting to work with basic functionality, Sending a request with data and receiving a response with data, then displaying it using jQuery and Rails This piece of code pertains to the frontend. $("#internal_btn").click(function() { //windo ...

Unable to update data from false to true in vue.js

What I'm trying to do is change the data from false to true in order to conditionally render a button when a payment has succeeded. When making an axios call, I receive 'succeeded' as the response in the JSON object and can log it to the con ...

The process of prioritizing specific elements at the top of an array when ordering

In my array, I want to prioritize specific items to always appear at the top. The API response looks like this: const itemInventorylocationTypes = [ { itemInventorylocationId: '00d3898b-c6f8-43eb-9470-70a11cecbbd7', itemInvent ...

What is the maximum file size that the data link is able to store?

For instance, a file like an image, video, or sound can be saved in the data link Take an image for example, it may be stored with the initial link: data:image/jpeg;base64,/..... followed by various characters. But, is there a specified size limit at whic ...

Displaying information from an array using AngularJS

I'm struggling to display data from an array and I could use some help. Here's a snippet from my service.js file: this.fetchData = function() { var myArray = $resource('url', {method: 'get', isArray: true}); myArray ...

Tips for adding npm modules in StackBlitz?

Is it possible to install npm packages for Angular on StackBlitz without a terminal? I'd like to know the process. ...

Encountered an issue in Typescript with error TS2554: Was expecting 0 arguments but received 1 when implementing useReducer and useContext in React

I've encountered several errors with my useReducers and useContext in my project. One specific error (TS2554) that I keep running into is related to the AuthReducer functionality. I'm facing the same issue with each Action dispatch. I've tri ...