0

I have two main div tags within my code: one is the main display (id = 'test') and the other is a loading screen (id = 'loading') that covers the whole screen while the main display is being fetched. The main display's div code is all being done through a javascript function. So far, here's what I have:

<body>
       <div class="container" id="test"></div>

       <div class="loader-wrapper" id="loading">
            <span class="loader"><span class="loader-inner"></span></span>
        </div>


    <script>
        $(window).on('load', function(){
          $('#loading').fadeOut();
        });
    </script>
</body>

For reference, "test" is handled by a js class I've created that fetches data from a localhost, which contains certain data to be displayed. The data is returned in the form of a dictionary. Based on the length of this dictionary, my code loops that many times and creates the innerHTML of test in a user-friendly format. If the data is empty, an else-statement is in place to display a different innerHTML for test. The code from the js function is as follows:

const renderTest = async function(){
    var row_string = "";
    var response = await fetch(`http://localhost:3000/getData`);
    const data = await response.json();
    //create the innerHTML of test
}
renderTest();

The issue I am having trouble solving is that the jquery function I made finishes before the "test" div is done being loaded. I tried substituting window with "#test" but found that the loading screen is always present with that. What's the best way to solve this? I would love to have a way where I can simply fadeOut the loading screen once renderTest is complete.

Ali Z
  • 1
  • 1
  • 1
    Well sounds like you should be binding an event to whatever is adding the content to the div.... So is it an Ajax call? – epascarello Jun 02 '20 at 23:31
  • I have not worked with Ajax, unfortunately. – Ali Z Jun 03 '20 at 17:58
  • `//create the innerHTML of test` <-- run code here, hide it there..... – epascarello Jun 03 '20 at 18:05
  • I'm sorry... I can't believe I didn't think of that. All I had to do was put the following at the very end of my code: $('#loading').fadeOut(); Thank you for your help lol – Ali Z Jun 03 '20 at 18:12

1 Answers1

0

As @epascarello says you should hide the loader from the function that is loading/fetching your div's content

If you're using Promises it should be like this

fetchData()
.then(ok => $('#loading').fadeOut(), er => alert("something went wrong: "+er)

If you are not using promises add your function that is loading your data so we can help.

Btw, is a good practice to use Promises when using loaders nowadays

HYAR7E
  • 194
  • 2
  • 10