Vipin
Vipin

Reputation: 153

show images one by one using fadein and fadeout in jquery

Today while creating a slider i stuck in the middle of code that how can i fadein and fadeout the image one by one in jquery. Code i tried so far:-

  <head>
  <style>
   #slideshow{
     list-style: none;
     width: 100%;
     height: 100%;
     top: 0;
     left: 0;
     padding: 0;
     margin: 0;
     position:fixed;
  }
  ul{
     list-style-type:none;
  }
 ul li{
     display:inline;
     width: 100%;
     height: 100%;
     position:absolute;
     background-size:cover;
     background-position:center center;
 }
 ul li img{
    display:none;
 }
 </style>
 </head>
<body>
<ul id="slideshow">
   <li><img src="img/1.jpg" /></li>
   <li><img src="img/2.jpg" /></li>
   <li><img src="img/3.jpg" /></li>
</ul>
<script>
    window.onload=init;
function init(){
items=$('ul').children('li');
i=0;
item=$(items[i]);
item.css('background-image','url('+ item.find('img').attr('src') +')').fadeOut(1000,function(){
    for(i=0;i<items.length;i++){
        item=$(items[i]);
        item.css('background-image','url('+ item.find('img').attr('src') +')');
    }
 });
}
</script>
</body>

After showing first image it automatically goes to last image without displaying the second image. Please help me to rectify this problem.

Upvotes: 0

Views: 2175

Answers (4)

Johan Karlsson
Johan Karlsson

Reputation: 6476

Here's how you can do it: JSFiddle

function init(){
    $("#slideshow li").each(function(index){
       this.style.backgroundImage = "url('" + this.children[0].src + "')"; 
        if( index != 0)
           this.style.display = "none"; 
    });

    setTimeout(changeImage, 4000);
}

function changeImage(){
    $curr = $("#slideshow .active");
    $next = $("#slideshow .active").next();

    if($next[0] === undefined)
        $next = $("#slideshow li").eq(0);

    $curr.fadeOut(1000, function(){
        $next.fadeIn(1000, function(){
            $curr.removeClass("active");
            $next.addClass("active");
            setTimeout(changeImage, 4000);  //change image every 4 seconds
        });   
    });                 
}

$(document).ready(init);

Upvotes: 1

Levi Beckman
Levi Beckman

Reputation: 533

There are definitely more than one way to do this.

I answered a similar question here:

>> Adding fade to simple slideshow with Javascript <<

However, to answer YOUR question directly, consider the following:

>> WORKING JS FIDDLE <<

// create arbitrary namespace
window.slideshow = {
    slides: null,
    currentSlide: null,
    nextSlide: null,
    interval: 3000,
    timer: null,
    init: function() {
        console.log('init slideshow');
        this.slides = $('#slideshow img');
        this.planNextSlide(1);
    },
    planNextSlide: function(timeoutInterval) {
        console.log('next slide (' + timeoutInterval + ')');
        this.timer = setTimeout(this.transitionSlide, timeoutInterval);
    },
    transitionSlide: function() {
        console.log('transition slide (' + (slideshow.currentSlide != null) + ')');
        if (slideshow.currentSlide != null) {
            // fade out old slide first
            slideshow.slides.eq(slideshow.currentSlide).fadeOut('fast', function() {
                slideshow.nextSlide = slideshow.currentSlide + 1;
                if (slideshow.nextSlide == slideshow.slides.size()) {
                    slideshow.nextSlide = 0;
                }
                slideshow.currentSlide = null;
                slideshow.transitionSlide();
            });
        }
        else {
            // fade in new slide
            slideshow.nextSlide = slideshow.nextSlide == null ? 0 : slideshow.nextSlide;
            slideshow.slides.eq(slideshow.nextSlide).fadeIn('fast', function() {
                slideshow.currentSlide = slideshow.nextSlide;
                slideshow.planNextSlide(slideshow.interval);
            });
        }
    }
};

// initial state initializer
slideshow.init();

Upvotes: 0

jiy
jiy

Reputation: 868

I'd suggest having a single element instead of 3.

Also, use a recursive function to swap the image every 2 seconds.

Lastly note the javascript has been moved inside the <head> element where it should be.

Update: This has been tested and works great - had to fix a few bugs - here's the updated code:

<html>
<head>
    <style><!-- Your Styles --></style>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script language="javascript">

        var imgNum = 1;

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

        function doSlideshow() {
            $('#image1').fadeOut(400, function() {
                $('#image1').attr('src', 'img/' + imgNum + '.jpg');
                $('#image1').fadeIn(400);
                imgNum++;
                if (imgNum == 4) { imgNum = 1; }
                setTimeout('doSlideshow()', 2000);
            });
        }

    </script>
</head>
<body>
    <ul id="slideshow">
       <li><img id="image1" src="" /></li>
    </ul>
</body>
</html>

Upvotes: 0

Mathieu Labrie Parent
Mathieu Labrie Parent

Reputation: 2606

You need to use the setInterval() and something must tell you what is the current img. Assume that all image is hidden exept for the active one.

<ul id="slideshow">
   <li class="active"><img src="img/1.jpg" /></li>
   <li><img src="img/2.jpg" /></li>
   <li><img src="img/3.jpg" /></li>
</ul>

function ShowNext()
{
    var current = $("#slideshow .active");
    $(current).removeClass("active");
    $(current).fadeOut(1000, function () {
        $(current).next().fadeIn(1000);
        $(current).next().addClass("active");

    });

}

setInterval(function() {
    ShowNext(); 
}, 4000);

Code not tested but this is how you should do it. Also you need to do something when you reach the end of the slider but i'm sure you can handle that.

Upvotes: 0

Related Questions