Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
Add and remove loading animation to ajax calls (jQuery)
// This code depends on jQuery
//create 1 global variable for namespacing purposes.
if (typeof tinyfly === 'undefined') {
tinyfly = {};
/* Handles adding and removing loading animations for ajax calls */
tinyfly.loading = (function($) {
var defaults = {},
add, remove;
// default options
defaults = {
size: 'large',
position: 'inside',
display: 'inline',
timeout: 100
Function: add
Adds loading animation markup into the DOM. Typically called on AJAX beforeSend.
(object) $el - jQuery object of the element that you want to insert the markup beside or into.
(object) options - The optional configuration settings.
(string) options.size {large, small} - determines the size of the animated gif spinner.
(string) options.position {before, after, inside} - Determines the jQuery insertion method.
(integer) options.timeout - number of miliseconds to wait before showing the spinner.
add = function($el, options) {
var settings = $.extend(defaults, options),
$markup, insertMarkup;
$markup = $('<span class="loader">loading&hellip;</span>')
.addClass(settings.size + ' ' + settings.position + ' ' + settings.display);
insertMarkup = function () {
//decide which DOM insertion to use
switch (settings.position) {
case 'before':
case 'after':
case 'inside':
//add timerId to the data blob so we can cancel it if the ajax call is quick
$'loading').timerId = settings.timerId;
//only show the loading animation if the ajax call takes longer the specified miliseconds
settings.timerId = window.setTimeout(insertMarkup, settings.timeout);
$'loading', settings);
Function: remove
Removes the markup inserted by the add function. Typically called on AJAX Complete.
(object) $el - jQuery object of the element on which to start DOM traversal
and find the loading animation markup to remove
See Also:
remove = function($el) {
var settings = $'loading'),
selector = 'span.loader',
//check if there is a timer, if so clear it so the spinner
//doesn't get added after the page has loaded
if (settings.timerId) {
//decide which DOM traversal to use
switch (settings.position) {
case 'before':
$span = $el.prev(selector)
case 'after':
$span = $
case 'inside':
$span = $el.children(selector)
//public methods
return {
add: add,
remove: remove
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.