Skip to content

Instantly share code, notes, and snippets.

@mattbell87
Created September 9, 2014 04:53
Show Gist options
  • Save mattbell87/8cf6bb6550e6b0a095f1 to your computer and use it in GitHub Desktop.
Save mattbell87/8cf6bb6550e6b0a095f1 to your computer and use it in GitHub Desktop.
jQuery plugin to cycle and fade through a set of classes - uses a CSS3 transition
//Fade set looping animation
$.fn.fadeset = function(animlength)
{
$(this).each(function()
{
//Create a fadehandler object
var fadehandler = new (function(obj)
{
this.obj = obj;
this.current = 0;
this.classes = [];
this.animlength;
this.construct = function()
{
//Find all the fade classes
var currentdata = $(obj).data('fadeclass1');
while (typeof currentdata != 'undefined')
{
this.classes.push(currentdata);
currentdata = $(obj).data('fadeclass' + (this.classes.length + 1));
}
if (this.classes.length > 1)
{
this.animlength = animlength/this.classes.length;
//Create CSS3 transition
$(this.obj).css("transition", "all " + this.animlength/1000 + 's');
//Start calling the updates
this.update();
}
}
this.update = function()
{
//Replace the current class with the next class
$(obj).removeClass(this.classes[this.current]);
this.current++;
if (this.current >= this.classes.length)
this.current = 0;
$(obj).addClass(this.classes[this.current]);
//Call next update
var fh = this;
setTimeout(function()
{
fh.update();
}, this.animlength);
}
this.construct();
})(this);
//Attach fadehandler to the jquery object
$(this).data("fadehandler", fadehandler);
});
};
<!DOCTYPE html>
<html>
<head>
<title>Fade test</title>
<script src="jquery.js"></script>
<script src="fadeset.js"></script>
<script src="usage.js"></script>
<style>
.myred {background: red}
.mygreen {background: green}
.myyellow {background: yellow}
</style>
</head>
<body>
<div class="fadeset"
data-fadeclass1="myred"
data-fadeclass2="mygreen"
data-fadeclass3="myyellow">
Test</div>
</body>
</html>
$(document).ready(function()
{
$('.fadeset').fadeset(3000);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment