Reputation:
I am trying to display an loading indicator for every ajax request, I working in a rails 3 app.
HTML:
<div id="loading-indicator">
<%= image_tag("loading.gif", :id => "loading-indicator", :style => "display:none") %>
</div>
CSS:
#loading-indicator {
position: absolute;
left: 10px;
top: 10px;
}
loading.js: which I placed in assest/javascripts/
$(document).ready(function(){
$(document).ajaxSend(function(event, request, settings) {
$('#loading-indicator').show();
});
$(document).ajaxComplete(function(event, request, settings) {
$('#loading-indicator').hide();
});
});
My application.js looks like this:
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require_tree .
It dosent work, nothing shows up. Any help would be appreciated.
Upvotes: 11
Views: 7440
Reputation: 15089
I usually have this piece of code saved to situations like these:
$(function() {
$('#loading-indicator')
.hide() // hide it initially.
.ajaxStart(function() {
$(this).show(); // show on any Ajax event.
})
.ajaxStop(function() {
$(this).hide(); // hide it when it is done.
});
});
--- EDIT ---
This will not work with the latest versions of jQuery. As of jQuery 1.8, the .ajaxStart()
method should only be attached to document
. The code should therefore look as follows:
$(function() {
$('#loading-indicator').hide(); // hide it initially.
$(document)
.ajaxStart(function() {
$('#loading-indicator').show(); // show on any Ajax event.
})
.ajaxStop(function() {
$('#loading-indicator').hide(); // hide it when it is done.
});
});
Upvotes: 16
Reputation: 108
You technically can't use the same "id" twice for two different elements in the same document. i.e. you are assigning id="loading-indicator" to both the div and the img tags; this might be causing JS DOM selection and manipulation errors.
Upvotes: 3
Reputation:
The problem was in the css style tag and the css position
I fix it by doing this:
HTML:
<div id="loading-indicator">
<%= image_tag("loading.gif", :id => "loading-indicator") %>
</div>
CSS:
#loading-indicator {
left: 10px;
top: 10px;
}
Upvotes: 0