Object Oriented Javascript Example

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?