Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fading between images

How can i fade rotate between two images using jQuery? Say for example.

<img src="image01.jpg" />
<img src="image02.jpg" />

I like the images to fade in/out between for say 2seconds each.

Thanks! Much appreciated. :)

like image 310
calebo Avatar asked Apr 13 '26 00:04

calebo


2 Answers

A simple example i knocked up.

<div id="imageSwap">
</div>  


 <script language="javascript" type="text/javascript">

    $(document).ready(function () {
      setImageOne();
    });

    function setImageOne() {
      $('#imageSwap').fadeIn(500).html('<img src="image01.jpg" />').delay(2000).fadeOut(500, function () { setImageTwo(); });
    }

    function setImageTwo() {
      $('#imageSwap').fadeIn(500).html('<img src="image02.jpg" />').delay(2000).fadeOut(500, function () { setImageOne(); });
    }

  </script>
like image 122
GordonB Avatar answered Apr 15 '26 16:04

GordonB


rewrite your html to

<div>
<img class="current slide" src="image01.jpg" style="position:absolute;"/>
<img class="slide" src="image02.jpg" style="position:absolute;display:none"/>
<img class="slide" src="image03.jpg" style="position:absolute;display:none"/>
<img class="dummy" src="image01.jpg" style="visibility:none;"/>
</div>

I added a 3rd image for clarity. Add a jquery function like

function nextSlide() {
    jQuery('.slide.current').each(function() {
        var next = jQuery(this).next('.slide');
        if (!next.size()) next = jQuery(this).siblings('.slide').eq(0);
        jQuery(this).fadeOut().removeClass('current');
        next.fadeIn().addClass('current');
    }); 
    slidetimer=setTimeout('nextSlide()',slidespeed);
}

And in your base javascript, add

var slidespeed = 2000;
var slidetimer = null;
jQuery(document).ready(function() {
    nextSlide()
});

I didnt test this exactly like this, so typoos may be there. The surrounding div ensures that all slide images are located on the spot where the div is located, because of their position:absolute. the dummy image is not visible, but does fill up the space needed to make the surrounding div actually wrap around all the images. You may not need this.

Your images should have similar sizes, or at least the dummy should be as big as the biggest image.

$2c, *-pike

like image 27
commonpike Avatar answered Apr 15 '26 16:04

commonpike