using jquery to transition between images

23,041

Solution 1

I think this would definitely help

http://addyosmani.com/blog/css3transitions-jquery/

also this

http://jquery-howto.blogspot.com/2009/05/replacing-images-at-time-intervals.html

here is a jquery plugin for this

http://plugins.jquery.com/project/bgImageTransition

Solution 2

I found this solution to be simple and suited my needs.

The gist of it is:

  1. Put all of the images you want to transition between in the same div.
  2. Set the class of one of them to something like "active"
  3. In the css, hide all of the images that don't have the class set to "active"
  4. User jquery selectors to grab the current "active" element, unclass it, and set the next (or first) image element in the div to the "active class. Use jquery fadeOut and fadeIn to handle the transitions.
  5. Use setInterval to handle the cycle timing.

Via: http://jquery-howto.blogspot.com/2009/05/replacing-images-at-time-intervals.html

<html>
<head>
  <script src="jquery.js">
  </script>
  <script>
    function swapImages(){
      var $active = $('#myGallery .active');
      var $next = ($('#myGallery .active').next().length > 0) ? $('#myGallery .active').next() : $('#myGallery img:first');
      $active.fadeOut(function(){
      $active.removeClass('active');
      $next.fadeIn().addClass('active');
      });
    }

    $(document).ready(function(){
      // Run our swapImages() function every 5secs
      setInterval('swapImages()', 5000);
    }
  </script>
  <style>
    #myGallery{
      position:relative;
      width:400px; /* Set your image width */
      height:300px; /* Set your image height */
    }
    #myGallery img{
      display:none;
      position:absolute;
      top:0;
      left:0;
    }
    #myGallery img.active{
      display:block;
    }
  </style>
</head>
<body>
  <div id="myGallery">
    <img src="image1.jpg" class="active" />
    <img src="image2.jpg" />
    <img src="image3.jpg" />
  </div>
</body>
</html>

Solution 3

Yes, you can put the new image on top of the current one, using absolute positioning, then use fadeTo to fade in the new image. You can use a simple setInterval to make this happen periodically.

EDIT: fadeTo lets you go to a specific level of transparency. Easier just to use fadeIn, which will go from 100% to 0% transparency.

Share:
23,041
Anthony
Author by

Anthony

Updated on June 01, 2020

Comments

  • Anthony
    Anthony about 4 years

    I have two images that are of same size and text but different colors (they are used as logos). I would like to slowly automatically transition between the two images using jQuery. First, I was going to make a GIF image out of the two images but then thought that perhaps jQuery can be used.

    Is this possible with jQuery?

    I want the transition to happen without any input from the user and it can happen every X seconds.

    Please let me know how this can be done.