redshot redshot - 9 days ago 6
CSS Question

How to show setTimeout image before showing content in jQuery?

I have button that has a on.click(function() {}. Inside the click function is a setTimeout( function() {} that will show the content from external html file.

<button type="button" class="btn btn-primary choose-iphone-btn">Jet Black</button>

$(function() {

$('.choose-iphone-btn').click(function() {

setTimeout( function() {

$.get('iphone-checkout.html')
.success(function(data) {
$('.iphone-pre-order-sales-content-info').html(data);
});

}, 3000);

});

});


I want to display

<img src="images/default.gif" />


for 3 seconds before showing iphone-checkout.html.

Any help is appreciated.

Answer

Set a class to your img, say loading

<img class="loading" src="images/default.gif" /> 

Show and hide the same within click event.

$('.choose-iphone-btn').click(function() {
     $(".loading").show(); //get reference to element with its class and show it
     setTimeout( function() {
         $.get('iphone-checkout.html')
           .success(function(data) {
              $(".loading").hide();//hide once your ajax is success
              $('.iphone-pre-order-sales-content-info').html(data);
        });
     }, 3000);
});

You can also hide the loading in .done event, so that even in ajax failure, it doesn't block your view or keep displaying it.

$('.choose-iphone-btn').click(function() {
     $(".loading").show(); //get reference to element with its class and show it
     setTimeout( function() {
         $.get('iphone-checkout.html')
           .success(function(data) {
              $('.iphone-pre-order-sales-content-info').html(data);
           });
           .done(function() {
              $(".loading").hide();//hide once your ajax request is done
           });
      }, 3000);
 });