Skip to content

Instantly share code, notes, and snippets.

@ct27stf
Created July 9, 2012 13:19
Show Gist options
  • Save ct27stf/3076524 to your computer and use it in GitHub Desktop.
Save ct27stf/3076524 to your computer and use it in GitHub Desktop.
A jQuery plugin to change the background image of an element from a list of images
/*===============================
Usage:
$(document).ready(function() {
$('body').changeBackground({
'path': '', // path to images (eg. /wp-content/themes/mytheme/ )
'images': [], // images list eg. ['img1.jpg', 'img2.jpg', 'img3.jpg']
'interval': 1000 // transition time in miliseconds
});
});
=================================*/
(function($){
$.ChangeBackground = function(el, options){
// To avoid scope issues, use 'base' instead of 'this'
// to reference this class from internal events and functions.
var base = this;
// Access to jQuery and DOM versions of element
base.$el = $(el);
base.el = el;
// Add a reverse reference to the DOM object
base.$el.data("ChangeBackground", base);
base.init = function(){
base.options = $.extend({},$.ChangeBackground.defaultOptions, options);
// Put your initialization code here
setInterval(base.setBackground, base.options.interval);
};
// Sample Function, Uncomment to use
base.setBackground = function(){
var poza = base.options.images[Math.floor(Math.random()*base.options.images.length)];
$(el).css('background-image', 'url('+ base.options.path + poza + ')');
};
// Run initializer
base.init();
};
$.ChangeBackground.defaultOptions = {
path: "",
images: [],
interval: 1000
};
$.fn.changeBackground = function(options){
return this.each(function(){
(new $.ChangeBackground(this, options));
});
};
// This function breaks the chain, but returns
// the ChangeBackground if it has been attached to the object.
$.fn.getChangeBackground = function(){
this.data("ChangeBackground");
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment