Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Change Image src with Fade Effect

Tags:

jquery

image

fade

I'm trying to create an effect where you click on a thumbnail image, and the link to the thumbnail will replace the main image, but fade it in. This is the code I'm currently using:

$(".thumbs a").click(function(e) {
    e.preventDefault();
    $imgURL = $(this).attr("href");
    $(".boat_listing .mainGallery").fadeIn(400, function() {
        $(".boat_listing .mainGallery").attr('src',$imgURL);
    });
});

This works and replaces the image without a fade effect. What do I need to change to get the fadeIn effect to work?

like image 429
WebDevDude Avatar asked May 12 '11 14:05

WebDevDude


3 Answers

You have to make it fadeOut() first, or hide it.

Try this :

$(".thumbs a").click(function(e) {
    e.preventDefault();
    $imgURL = $(this).attr("href");
    $(".boat_listing .mainGallery")
        .fadeOut(400, function() {
            $(".boat_listing .mainGallery").attr('src',$imgURL);
        })
        .fadeIn(400);
});

It should fadeOut the image, then change the src when it's hidden, and then fadeIn.

Here's a jsFiddle example.

Edit: you can find a more recent & better solution in Sandeep Pal's anwser

like image 104
Sylvain Avatar answered Nov 12 '22 05:11

Sylvain


I thing instead of using FadeIn and fadeOut, its better to use fadeTo functionality as fadeIn and fadeOut created a time gap between them for few micro-seconds.

I have used above code from Sylvain : thanks to him

$("#link").click(function() {

  $("#image").fadeTo(1000,0.30, function() {
      $("#image").attr("src",$("#link").attr("href"));
  }).fadeTo(500,1);
  return false;
});
like image 35
Sandeep Pal Avatar answered Nov 12 '22 07:11

Sandeep Pal


I reproduced the given samples above. It gives a strange flickering, which I found that it waits for image to load after it's opacity is restored to 1. I modified the code by Sandeep.

$("#link").click(function() {

$("#image").fadeTo(1000,0.30, function() {
  $("#image").attr("src",$("#link").attr("href"));
  $("#image").on('load', function(){
    $("#image").fadeTo(500,1);
  });
 });
 return false;
});`
like image 4
Aamir Hussain Avatar answered Nov 12 '22 06:11

Aamir Hussain