Search code examples
jqueryimagefadeinfade

Adding fade to jQuery image swap


I'm building an app to display different colours of a car when the colour swatch is clicked. I've built the jQuery to nicely swap out the image based on the swatch that is clicked.

However, I'm struggling to make the new image fade in nicely over the one that is already visible.

$('a.swatchItem').click(function() { // on click of swatch
    var carID = $(this).attr('id'); // grab the clicked ID
    $('a.swatchItem').removeClass('active'); // Remove active class
    $(this).addClass('active'); // Add active class to current swatch
    $("#carItem").attr('src',"img/models/longtitude/" + carID + ".png"); // replace with new car image
    return false;
});

Thanks


Solution

  • You can try with this:

    $('a.swatchItem').click(function() { // on click of swatch
      var carID = $(this).attr('id'); // grab the clicked ID
      $('a.swatchItem').removeClass('active'); // Remove active class
      $(this).addClass('active'); // Add active class to current swatch
      $("#carItem").fadeOut('fast', function(){
          $(this).attr("src", "img/models/longtitude/" + carID + ".png").fadeIn();
      }); // replace with new car image
      return false;
    });
    

    A simple fiddle demo.