Vikrant Chaudhary | December 01, 2011 | Tagged
javascript,
rails-3
Here’s how you can display a spinner on each Ajax request in Ruby on Rails 3 using jQuery and HTML5 “data-” attributes.
The setup part
//public/javascripts/application.js
//"ajax:beforeSend" and "ajax:complete" event hooks are provided by Rails 3's jquery-ujs driver.
$("*[data-spinner]").live('ajax:beforeSend', function(e){
$($(this).data('spinner')).show();
e.stopPropagation(); //Don't show spinner of parent elements.
});
$("*[data-spinner]").live('ajax:complete', function(){
$($(this).data('spinner')).hide();
});
#app/helpers/application_helper.rb
def spinner_tag id
#Assuming spinner image is called "spinner.gif"
image_tag("spinner.gif", :id => id, :alt => "Loading....", :style => "display:none")
end
The effect part
Now in whichever form or link you’d like to add spinner support just add one “data-spinner” attribute and the spinner image.
Here’s an example -