0

I developed the below image changer with JQuery:

var images = [];
images[0] = "image1.jpg";
images[1] = "image2.jpg";

var i = 0;
setInterval(fadeDivs, 3000);

function fadeDivs() {
    i = i < images.length ? i : 0;
    $('.slideshow-right-corner img').fadeOut(100, function(){
        $(this).attr('src', images[i]).fadeIn(100);
    })
    i++;
}

For some reason, it works fine locally, however when I integrate with my website, it works fine for the first image in the array and stops working. The following is the error I receive when I inspect the element:

Uncaught TypeError: undefined is not a function (index):398 (anonymous function) (index):398 E.complete jquery-1.3.2.min.js?ver=3.4.1:19 o.fx.step jquery-1.3.2.min.js?ver=3.4.1:19 F jquery-1.3.2.min.js?ver=3.4.1:19 (anonymous function)

4
  • 2
    What are the differences between your live and test environment? Same versions of jQuery and any other plugins etc? Commented May 9, 2014 at 10:03
  • have all the script include correctly? Commented May 9, 2014 at 10:04
  • 2
    Needles to say, jQuery 1.3.2 is really, really old (~5 years, 2009). Commented May 9, 2014 at 10:04
  • 2
    use latest jquery if possible Commented May 9, 2014 at 10:05

3 Answers 3

1

The problem is multithreading. The i++ will be evaluated before the fadeOut function.

So when i=2 images[2] will return undefined and the program will stop working.

Try to move i++ inside the function, after fading in.

This is the updated code (TESTED):

function fadeDivs() {
   i = i < images.length ? i : 0;
   $('.slideshow-right-corner img').fadeOut(100, function() {
   $(this).attr('src', images[i]).fadeIn(100);
   i++;
});
Sign up to request clarification or add additional context in comments.

1 Comment

and i = i < images.length ? i : 0; as well while you're at it
0

Working JSBIN DEMO

function fadeDivs() {
  $.each(images, function(e) {
     $('.slideshow-right-corner img').fadeOut(100,    function(){
        $(this).attr('src', images[e]).fadeIn(100);
    });
 });
}

You can remove the i variable outside the function.

2 Comments

The demo is not working. Try to use different images (and not the same one repeated) and only only will be displayed.
What's the reason for doing var self = e;? Just use images[e], much simpler.
0

As @Stefano Altieri said, the i variable is increased before the ending of the fadeIn function. Replace the fadeDivs function with this:

function fadeDivs() {
    i = i < images.length ? i : 0;
    $('.slideshow-right-corner img').fadeOut(100, function(){
        $(this).attr('src', images[i]).fadeIn(100, function(){
            i++;
        });
    })
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.