Search code examples
jquerycssopacityfade

jQuery crossfade images and hide them with display:none


I need to fade a div with a background-image to another in the same container with fixed dimension.

FadeIn and Out are what I need and work quite well, because I want the possibility to click on each visible image, and that's impossible working with opacity, even if it's exactly the effect I'd like to have.. a kind of crossfading between the images.

HTML

<div class="image_container">
    <div id="image1"></div>
    <div id="image2" style="display:none"></div>
</div>

my simplified js

$( this ).click(function() {
  $( "#image1" ).fadeOut();
   $( "#image2" ).fadeIn();
}

Solution

  • By placing images in an absolute position on top of each other, you can use jQuery to fade between them like this:

    <div class="image_container">
      <div id="image1"></div>
      <div id="image2" style="display:none"></div>
    </div>
    
    <script type="text/javascrtip">
      $(".image_container").click(function(){
        $(this).find("div").fadeOut();
        $(this).find("div:hidden").fadeIn();
      })
    </script>
    
    <style type="text/css">
      .image_container div {
        position:absolute;
        width:338px;
        height:225px;
        top:0;
        left:0;
      }
    
      #image1 {
        background-image:url(http://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg);
      }
    
      #image2 {
        background-image:url(http://imaging.nikon.com/lineup/dslr/df/img/sample/img_02.jpg);
      }
    </style>
    

    Here's a Fiddle to demonstrate: https://jsfiddle.net/zmur2v8q/1/

    Simply click on the image to fade into the other one.