I the following code I have a UL with x3 LI’s. I want the LI’s to fadeIn in a sequence but am loosing scope somewhere I think. The problem is that only the last item in the sequence is run. I initially thought this was to do with a loop, so I removed all of them. Any help would be great.
Thanks is Advance.
function Sequence() {
var sequence = [];
var pos = 0;
Sequence.prototype.add = function(obj) {
sequence.push(obj);
};
Sequence.prototype.start = function() {
sequence[pos].run();
};
Sequence.prototype.next = function() {
pos++;
sequence[pos].run();
};
};
function fadeIn(params) {
this.id = params.id;
this.onComplete = params.onComplete;
var self = this;
var timer;
var i = params.opacity;
fadeIn.prototype.run = function(){
timer = setInterval(function() {
params.element.style.opacity = i / 10;
i++;
if (i / 10 == 1) {
clearInterval(timer);
self.onComplete();
}
}, params.fps);
}
};
var sequence = new Sequence();
var fader = document.getElementById('fader1');
var items = fader.getElementsByTagName("li");
sequence.add(new fadeIn({
"id": "instance_0",
"element": items[0],
"opacity": 0,
"fps": 80,
"onComplete": function() {
sequence.next();
}
}));
sequence.add(new fadeIn({
"id": "instance_1",
"element": items[1],
"opacity": 0,
"fps": 80,
"onComplete": function() {
sequence.next();
}
}));
sequence.start();
Yes, this is a scope issue. The problem is in the line:
When you define a method on the
prototype, you’re defining the method on all instances of thefadeInclass. So each time you call the constructor, you’re redefining the method with the newparamsin the closure.The solution is to define the method on
this(or, as you’ve renamed it,self), which is the new instance, rather than the class:Working example here: http://jsfiddle.net/nrabinowitz/wrQMa/3/