Mask
Mask

Reputation: 34207

How to smoothly change <img src="..." /> with jQuery?

I'm now doing something like :

$img.hover(function(){$(this).attr('src','1.jpg')},function(){$(this).attr('src','2.jpg')});

Which is not smooth,because it takes quite some time to load an image.

Upvotes: 4

Views: 3615

Answers (4)

Erez Lieberman
Erez Lieberman

Reputation: 2027

perload the image and put it in div that have a opacity:0;height:0;width:0;

preload_url = $(this).data('hover_image');
$('body').append('<div style="opacity:0;height:0;width:0"><img src="'+preload_url+'"></div>');

Upvotes: 0

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827416

What about pre-loading your images when the page loads:

$(function () {
  var preloadImages = ['1.jpg', '2.jpg'];

  $.each(preloadImages, function () {
    $('<img/>').attr('src', this);
  });

  // ...
});

Upvotes: 8

NawaMan
NawaMan

Reputation: 25687

Try this: Load image and swap when done or Preload image when page load.

Upvotes: 0

rahul
rahul

Reputation: 187050

Change that to a background image with both the images combined and change the background position dynamically.

Use CSS sprites.

If you need to stick with an image itself then preload the two images and then it will take the second image from the cache which won't cause the delay.

Preloading Images With CSS

Upvotes: 5

Related Questions