user1182960
user1182960

Reputation: 5

Ajax preloader working only once

I have this script:

$(function() {
$(this).ajaxStart(function() {
$("#loading").show(); });
$(this).ajaxStop(function() {
$("#loading").hide(); });
});

$(document).ready(function() { 
$('.button').click(function () {
$("#contentDiv").load("content.php");
});

$('.button2').click(function () {
$("#contentDiv").load("content2.php");
});
});

And this html:

<div id="contentDiv">
<div id="loading"></div>

</div>

I want to show loading .gif before every new load, but now it works only first time whole page is loaded. So when I click first time "button", "loading" shows, "content" is loaded and "loading" hides. When I than click "button2", "content2" is loaded but "loading" did not shows. I try to take out "loading" div from "contentDiv", but than "loading" never hides.

Upvotes: 0

Views: 1452

Answers (4)

kaizenCoder
kaizenCoder

Reputation: 2229

An ID is meant to be a single unique instance on your page. On the other hand a Class can be reused multiple times. So really the following change alone should work:

<div class="loading"></div>

Upvotes: 0

user1182960
user1182960

Reputation: 5

I made it working this way:

$(document).ajaxStart(function() {
$('.loading').show();
$('#contentDiv').hide();
}).ajaxStop(function() {
$('.loading').hide();
$('#contentDiv').show();
});

html:

<div id="contentDiv"></div>
<div class="loading"></div>

I have to made loading div class because ID was not working.

Upvotes: 0

Anthony Grist
Anthony Grist

Reputation: 38345

You're replacing the content of #contentDiv, which contains the #loading div, so it may no longer exist after calling .load() if the div isn't also present in content.php or content2.php. It may appear as if your code works fully the first time, but rather than simply hiding #loading you're actually removing it entirely.

If that's not the problem, then it's possible that the AJAX calls complete quickly enough that the element is shown, and then hidden again, fast enough that you can't see it happen.

Upvotes: 1

xkeshav
xkeshav

Reputation: 54084

write

<div id="loading" style="display:none"></div>

above the

<div id="contentDiv">

Upvotes: 1

Related Questions