Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Object Oriented Javascript Example
/*
*
* numfader
* by Gavin Blair
* http://github.com/gavinblair
*
* usage:
* //create a new numfader object on an element
* var myfader = new numfader(document.getElementById("mydiv"));
*
* //Count from 0 to 100, at interval 10, then show a message
* myfader.animateText(
* 0, //from
* 100, //to
* 10, //interval
* function(){ //finished callback
* alert('Wow!');
* }
* );
*
* //Animate the background colour of the element, then show a message
* myfader.animateBackgroundColour(
* {r:255, g:0, b:0}, //from colour
* {r:0, g:255, b:0}, //to colour
* 10, //interval
* function(){ //finished callback
* alert('wow');
* }
* );
*
**/
var numfader = function(el){
//initialize
numfader.prototype.el = el;
this.animateText = function(from,to,interval,callback) {
if(interval === undefined) {
interval = 100;
}
var i = from;
var timer = setInterval(function(){
i = _incrementNum(i,to);
el.innerHTML = i;
if(i === to) {
clearInterval(timer);
if(callback){
callback(el);
}
}
}, interval);
};
this.animateBackgroundColour = function(fromRGB,toRGB,interval,callback){
if(interval === undefined) {
interval = 10;
}
var r = fromRGB.r;
var g = fromRGB.g;
var b = fromRGB.b;
var timer = setInterval(function(){
r = _incrementNum(r,toRGB.r);
g = _incrementNum(g,toRGB.g);
b = _incrementNum(b,toRGB.b);
el.style.backgroundColor = 'rgb('+r+','+g+','+b+')';
if(r === toRGB.r && g === toRGB.g && b === toRGB.b) {
clearInterval(timer);
if(callback){
callback(el);
}
}
}, interval);
};
function _incrementNum(from,to){
var i = from;
if(i < to) {
i ++;
} else if (i > to) {
i --;
}
return i;
}
};

March 20, 2013 - This is an example of object oriented programming with Javascript.

Typically we've done everything in $(document).ready() with listeners.

If we instead pull similar functionality into a Javascript plugin (which is way easier than it sounds), we can reuse it across multiple sites easily.

Here is the code for my numfader plugin. It has two functions - it can count inside an element from one number to another at a specified speed, and it can animate the background colour of an element.

Here are some usage examples of numfader:

//create a new numfader object on an element
var myfader = new numfader(document.getElementById("mydiv"));

//Count from 0 to 100, at interval 10, then show a message
myfader.animateText(
  0,          //from
  100,        //to
  10,         //interval
  function(){ //finished callback
    alert('Wow!');
  }
);

//Animate the background colour of the element, then show a message
myfader.animateBackgroundColour(
  {r:255, g:0, b:0},  //from colour
  {r:0, g:255, b:0},  //to colour
  10,                 //interval
  function(){         //finished callback
    alert('wow'); 
  }
);

gav

Comments?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment