RGrun RGrun - 7 months ago 12
Javascript Question

Javascript, Array no longer array when passed into function

I'm trying to write a script that displays a series of client testimonials, toggling the visibility of each one in order. I'm trying to use a queue to do this, and was told to use a regular Javascript array, which has the methods

push()
and
shift()
that enable queue functionality. However, when I try to pass the array into the function I wrote, I get this error:

TypeError: q.shift is not a function


So, somehow, the array I'm passing into the function is no longer an array somehow. Can someone more experienced with Javascript explain why this is happening?

Code:

function testimonials(q) {
var e = q.shift();

jQuery(e).fadeToggle("slow", testimonials(q.push(e)));

}

jQuery(document).ready(function() {

var elements = jQuery(".fade-text").toArray();

var queue = [];

// add to queue
for (i = 0; i < elements.length; i++) {
queue.push(elements[i]);
}

testimonials(queue);
});

Answer

Here is the problem testimonials(q.push(e)), the return value of push is a number and that doesn't have a method called shift().

 jQuery(e).fadeToggle("slow",function(){ testimonials((q.push(e), q)) });

Also you are not using the callBack of fadeToggle properly, you are calling the function testimonials immediately. Wrap that function call in an anonymous function and pass it as a callBack.