Sarchophagi
Sarchophagi

Reputation: 386

Change image Src only while animating its margin-left

For a browser game purpose i want to change an image src to an animated gif only while the image is being animated.

$(the_image_selector).animate({marginLeft: amount}, time);

How can i do it?

My idea is to change the image to the gif before calling animate, then use animate's callback to change back the image. Will it work?

Upvotes: 0

Views: 404

Answers (4)

kpblc
kpblc

Reputation: 902

you can run function then animation is complet. from jquery.com

$( "#clickme" ).click(function() {
  $( "#book" ).css('background-image','any-image.gif');
  $( "#book" ).animate({
    opacity: 0.25,
    left: "+=50",
  }, 5000, function() {
  // Animation complete.
     $( "#book" ).css('background-image','any-image.png');
  });
});

Upvotes: 2

SW4
SW4

Reputation: 71230

Demo Fiddle

As noted in my comment this will work:

var src = $('img').attr('src');
$('img').attr('src', 'https://disney-animation.s3.amazonaws.com/uploads/production/project_image/frozen/72/image/project_image.jpg');
$('img').animate({
    marginLeft: '100px'
}, 2000, function () {
    $(this).attr('src', src);
});

Upvotes: 0

Andreas
Andreas

Reputation: 685

Yes, I do think your strategy will work, for example

var image = $(the_image_selector);

image.attr('src', 'url to show while animated');

image.animate({marginLeft: amount}, time, function(){
    image.attr('src', 'normal url');
});

Upvotes: 2

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85643

Use like this:

$(the_image_selector).css('background-image','path-to-image');
$(the_image_selector).animate({marginLeft: amount}, time);

Or, combine like this:

$(the_image_selector).css('background-image','path-to-image').animate({marginLeft: amount}, time);

Or, if you want to change img's src then:

$(the_image_selector).attr('src','path-to-image').animate({marginLeft: amount}, time);

Upvotes: 0

Related Questions