1 <script type="text/javascript">
2 /**
3 * @constructor Animate
4 * @param {HTMLElement} el the element we want to animate
5 * @param {String} prop the CSS property we will be animating
6 * @param {Object} opts a configuration object
7 * object properties include
8 * from {Int}
9 * to {Int}
10 * time {Int} time in milliseconds
11 * callback {Function}
12 */
13 function Animate(el, prop, opts) {
14 this.el = el;
15 this.prop = prop;
16 this.from = opts.from;
17 this.to = opts.to;
18 this.time = opts.time;
19 this.callback = opts.callback;
20 this.animDiff = this.to - this.from;
21 }
22 /**
23 * @private
24 * @param {String} val the CSS value we will set on the property
25 */
26 Animate.prototype._setStyle = function(val) {
27 switch (this.prop) {
28 case 'opacity':
29 this.el.style[this.prop] = val;
30 this.el.style.filter = 'alpha(opacity=' + val * 100 + ')';
31 break;
32 default:
33 this.el.style[this.prop] = val +'px';
34 break;
35 };
36 };
37 /**
38 * @private
39 * this is the tweening function
40 */
41 Animate.prototype._animate = function() {
42 var that = this;
43 this.now = new Date();
44 this.diff = this.now - this.startTime;
45 if(this.diff > this.time) {
46 this._setStyle(this.to);
47 if(this.callback) {
48 this.callback.call(this);
49 }
50 clearInterval(this.timer);
51 return;
52 }
53 this.percentage = (Math.floor((this.diff / this.time) * 100) / 100);
54 this.val = (this.animDiff * this.percentage) + this.from;
55 this._setStyle(this.val);
56 };
57
58 /**
59 * @public
60 * begins the animation
61 */
62 Animate.prototype.start = function() {
63 var that = this;
64 this.startTime = new Date();
65 this.timer = setInterval(function() {
66 that._animate.call(that);
67 }, 4);
68 };
69 /**
70 * @static
71 * @boolean
72 * allows us to check if native CSS transitions are possible
73 */
74 Animate.canTransition = function() {
75 var el = document.createElement('twitter');
76 el.style.cssText = '-webkit-transition: all .5s linear;';
77 return !!el.style.webkitTransitionProperty;
78 }();
79 </script>
80
81 <script type="text/javascript">
82 (function() {
83 var blocking = false;
84 document.getElementById('click').onclick = function(e) {
85 if(blocking) {
86 return false;
87 }
88 blocking = true;
89 var that = this;
90 var el = document.getElementById('test');
91 var from = this.className == 'animated' ? 1 : 0;
92 var to = from == 1 ? 0 : 1;
93 // relevant stuffs
94 if(Animate.canTransition) {
95 el.style.webkitTransition = 'opacity 0.5s ease-out';
96 el.style.opacity = to;
97 blocking = false;
98 that.className = that.className == 'animated' ? '' : 'animated';
99 } else {
100 new Animate(el, 'opacity', {
101 from : from,
102 to : to,
103 time : 500,
104 callback : function() {
105 that.className = that.className == 'animated' ? '' : 'animated';
106 blocking = false;
107 }
108 }).start();
109 }
110 return false;
111 };
112 })();
113 </script>