nathan hartmann nathan hartmann - 1 year ago 63
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

without extra code

Answer Source

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.

var menuimage=$("#menuImage")
var cars = ['', ''];
var i = 0;
    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)