Josh O'Connor
Josh O'Connor

Reputation: 4962

Spinner while data from API is pulled (Javascript)

I have an html document which is gathering data from an api. As the data is being retrieved, there is a loadtime, usually 1-3 seconds. I want to incorporate a spinner or some sort, whether spin.js or a gif, while the data is loading, so the user knows data is being retrieved. How do I go about adding a spinner while the data is being loaded, to the function loaddata()?

Here is my code:

<script type="text/javascript" src="http://api.eventful.com/js/api"></script>
<script type="text/javascript">
    //Function which loads data from API.
    function loaddata() {
        //get vars 
        var oArgs = {
            app_key: "(HIDDEN FOR SECURITY PURPOSES)",
            q: "music",
            where: "San Diego", 
            "date": "2013061000-2015062000",
            page_size: 5,
            sort_order: "popularity",
        };

        var content = '';

        //API CALL
        EVDB.API.call("/events/search", oArgs, function(oData) {
            console.log(oData)
            //Get the title for each item
            for (var i = 0;i < oData.events.event.length;i++) {
                content += oData.events.event[i].title + '<br><br>';
            }

            // Show Data on page
            $("#ListItems").html(content);
        });
    }
</script>
<body>
    <input type = "button" id="target" value="search" onclick="loaddata();"/>
    <br><br>

    //Where Data is presented.
    <span id = "ListItems"></span>
</body>
</html>

Upvotes: 0

Views: 438

Answers (1)

Brian Glaz
Brian Glaz

Reputation: 15666

The typical way to achieve this is to show the spinner / loading graphic when the remote data is requested, and to hide the spinner when the request completes. In your case you could do something like the following:

$spinner = $('#loadingSpinner'); //element that contains spinner

//API CALL
$spinner.show();

EVDB.API.call("/events/search", oArgs, function(oData) {
    console.log(oData)
  // Hide spinner
  $spinner.hide();
  //Get the title for each item
  for (var i = 0;i < oData.events.event.length;i++){
    content += oData.events.event[i].title + '<br><br>';
  }
      // Show Data on page
      $("#ListItems").html(content);
    });
}

Upvotes: 1

Related Questions