nathan hartmann nathan hartmann - 1 month ago 8
jQuery Question

Putting .attr inside a function of another method breaks jquery

Below I have posted a JSfiddle. I am trying to use a for loop and an array list to change an image within my Jquery. for some reason this code works just fine when I only put it in:

menuimage.delay(500).attr('src', cars[i]);


but when I put

menuimage.delay(2000).toggleClass('nopacity', 1000, function(){
menuimage.delay(500).attr('src', cars[i]);
});
menuimage.delay(500).toggleClass('nopacity', 1000);


the image changing seems to break. I am not sure about why this is so. below I have posted JSfiddle of it. I've gotten the lower code to change the image I've wanted to correctly when it's outside of the array but inside it refuses to work while set up in this function off another setup. Any help and explanation would be appreciated.

with extra code

https://jsfiddle.net/nathanahartmann/hnkokka8/3/

without extra code

https://jsfiddle.net/nathanahartmann/2xk7jzd5/1/

Answer

Use setInterval instead of a for loop and also to know have a toggleClass Callback you need to use it like .promise().done(function(){});

The jQuery has promise method that returns a deferred object that you can access using .promise(). This promise object will be resolved after all running animations on selected elements are complete. At that point, you can bind to it's done method.

$("document").ready(function(){
var menuimage=$("#menuImage")
var cars = ['http://www.freedigitalphotos.net/images/img/homepage/87357.jpg', 'http://i164.photobucket.com/albums/u8/hemi1hemi/COLOR/COL9-6.jpg'];
var i = 0;
  setInterval(function(){
    menuimage.delay(2000).toggleClass('nopacity', 1000).promise().done(function(){
      menuimage.delay(500).attr('src', cars[i]);
    });
    menuimage.delay(500).toggleClass('nopacity', 1000);
    i ++;
    i = i % 2;
  }, 5000)

})

JSFIDDLE