Using jQuery deferred

by Gil Barbara

HTML

<div class="box"><div>Loading...</div></div>

CSS

.box {
    background-color: #999;
    color: #FFF;
    height: 300px;
    width: 300px;
}

.box > div {
    padding: 30px;
}

.box img {
    max-width: 100%; 
}
}

JavaScript

var app = {};

(function() {
    app.ready = $.Deferred();
    app.response = null;
    
    var hiding = $('.box').animate({ height: 0 }, 1000).promise();
    var json = $.getJSON('http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=Daft+Punk&api_key=24dd305e5bce31527a8c6178a7e4ce5c&format=json');
    
    $.when(hiding, json)
    .done(function(hidingResp, jsonResp) {
        if (jsonResp[0].error) {
            $('.box').after('Error loading json')
        }
        else {
            response = jsonResp[0];
            app.ready.resolve();
        }
    })
    .fail(function() {
        $('.box > div').html('failed').parent().animate({ height: 300 });
    });
})();

    app.ready.done(function () {
        $('.box > div').html('<img src="' + response.artist.image[4]['#text'] + '"/><br>' + response.artist.name + ' is playing in my code').parent().animate({ height: 300 }, 2000);
    });