0

I have the following HTML

<a href="/loadme.html" class="next">Load this content</a>
<a href"/loadmeto.html" class="next">Load some other content</a>

<div id="ajaxcontent"></div>
<div id="ajaxloader">*obligatory animated gif*</div>

And the following jquery which first loads some content on initial page load, and then subsequently overwrites it with other content when the .next buttons are clicked:

// Load the default initial content 
$(document).ready(function() {
$('#ajaxcontent').load('/keyplate/1');
});

// Dynamically GET the content via Ajax
$(document).on("click", ".next", function(){
    var link = $(this).attr('href');

    $('#ajaxcontent').fadeOut('fast', function() {
        $.get(
            link +' #ajaxcontent', 
            function(data) {
                $("#ajaxcontent").html(data).fadeIn('fast');
            }, 
            "html"
        );

    });
    return false;

});

What I need some help on is how I can show/hide the loading div:

a) initially when the page is loading the default content; and b) subsequently when the .next href content is being loaded

Thanks in advance!

vibe9
  • 33
  • 3
  • 11

2 Answers2

0

Try this using ajaxStart() & ajaxStop() methods:

HTML

<div id="ajaxloader">
    <img src="/images/ajax-loader.gif" alt="Loading..."/>
</div>

CSS:

div#ajaxloader
{
    display: none;
    width:100px;
    height: 100px;
    position: fixed;
    top: 50%;
    left: 50%;
    text-align:center;
    margin-left: -50px;
    margin-top: -100px;
    z-index:2;
    overflow: auto;
}  

JS

$('#ajaxloader').ajaxStart(function () {
    $(this).fadeIn('fast');
}).ajaxStop(function () {
    $(this).stop().fadeOut('fast');
});

This will show a loading image whenever an Ajax request starts and hide it too when the Ajax request stops.

palaѕн
  • 72,112
  • 17
  • 116
  • 136
  • Thanks - that sort of worked (maybe I'm just not dropping that in correctly, not sure how/where it would fit into the function syntax. I've come up with another way, but it's probably not that efficient - happy to see an improved method. – vibe9 Apr 05 '13 at 19:18
0

Here's what I came up with that works, but not sure it's so efficient - happy to hear better alternatives :-)

// Load the default initial content 

$(document).ready(function() {
    $('#ajaxcontent').load('/keyplate/1');
});

$(document).ajaxComplete(function() {
    $("#ajaxloader").hide();
});

// Dynamically GET the content via Ajax
$(document).on("click", ".next", function(){
    var link = $(this).attr('href');

    $('#ajaxcontent').fadeOut('fast', function() {
        $("#ajaxloader").show();
        $.get(
            link +' #ajaxcontent', 
            function(data) {
                $("#ajaxcontent").html(data).fadeIn('fast');
            $("#ajaxloader").hide();
            }, 
            "html"
        );

    });
    return false;

});
vibe9
  • 33
  • 3
  • 11