Hi,
I wahnt to write a jQuery plugin which will change the x background-position in an looped time interval.
$('#element').pluginName();
- starts the looped action
Then I wahnt to stop it by $('#element').stopFunction();
or $('#element').pluginName().stopFunction();
Is it possible? Can You give me a tip how to write it?
EDIT (my solution):
var LoadingAjax = function(element, options){
var element = $(element);
var object = this;
var defaults = {
width: 30,
gap : 1,
interval : 100,
maxFrame: 8
};
var settings = $.extend(defaults, options || {});
var timer;
var frame = 1;
var is_loading;
// Public method
this.startAnimate = function(){
console.log('start animate');
is_loading = true;
timer = setTimeout(loop, settings.interval);
};
this.stopAnimate = function(){
console.log('stop animate');
is_loading = false;
clearTimeout(timer);
};
this.isLoading = function(){
return is_loading;
}
// Private method
var loop = function(){
console.log('frame: '+frame);
if(frame < defaults.maxFrame){
element.css('background-position', '-'+(frame*(defaults.width+defaults.gap))+'px 0');
frame++;
}
else{
element.css('background-position', '0 0');
frame = 1;
}
timer = setTimeout(loop, settings.interval);
};
};
$.fn.loadingAjax = function(options){
return this.each(function(){
var element = $(this);
// Return early if this element already has a plugin instance
if (element.data('loader')) return;
// pass options to plugin constructor
var plugin_instance = new LoadingAjax(this, {});
// Store plugin object in this element's data
element.data('loader', plugin_instance);
});
};
$(document).ready(function(){
$('a#start').click(function(){
var loadingElement = $('.loading.ajax');
loadingElement.loadingAjax();
var plugin_instance = loadingElement.data('loader');
if(plugin_instance.isLoading() === true){
plugin_instance.stopAnimate();
}
else{
plugin_instance.startAnimate();
}
});
});
This link was very helpful: http://www.virgentech.com/blog/2009/10/building-object-oriented-jquery-plugin.html