Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Ryley Ameden
Ryley Ameden
220 Points

Javascript + Ajax: loading "gif" or wait message till everything is returned.

Hello,

I have an Javascript + Ajax app that goes out to an API and get some information and then displays it on the same page. There is some lag time for this to happen and right now the user is just forced to wait without knowing if it is actually doing anything. I would love to find a way to add a spinner or something to let them know that it is working. I was hoping someone would be able to help me out here.

Thanks, Ryley

1 Answer

Thomas Nilsen
Thomas Nilsen
14,957 Points

For example; let's say you have this in the html: I used this spinner

<span ng-show="isSpinning"><i class="fa fa-spinner fa-spin fa-3x fa-fw"></i></span>

In your javascript code (I'm assuming angular here, but the pattern will be the same anyway):

vm.isSpinning = false;

function getData() {
    //Set spinner visible
    vm.isSpinning = true;

    //Async call starts here 
    $http.get(url).then(function(response) {
        //hide spinner - because when we get here, we have out data.
        vm.isSpinning = false;

        //do something with data here...
    })
    .catch(function(err){
        console.log(err);
    });
}

The whole point is -

Use a boolean variable to show/hide an loading animation. When the callback is complete (i.e.e you have data) set the boolean to false which hides the animation.