Skip to content Skip to sidebar Skip to footer

Fadein() Images In Slideshow Using Jquery

I am working on an image slideshow, and the fadeOut() functionality working with every image change, but the next image appears abruptly. I want it to fade in. I can't seem to get

Solution 1:

I'd recommend something like this for your interval function:

window.setInterval(function (){
  var images = $('#backgroundChanger img');
  var active, next;

  images.each(function(index, img) {
    if($(img).hasClass('active')) {
      active = index;
      next = (index === images.length - 1) ? 0 : index + 1;
    }
  });

  $(images[active]).fadeOut(1000, function() {
    $(images[next]).fadeIn(1000);
  });

  $(images[next]).addClass('active');
  $(images[active]).removeClass('active');
}, 3000);

And this is all you'd need for your css:

#backgroundChangerimg:first-child {
  display: block;
}

#backgroundChangerimg {
  display: none;
}

And keep the same HTML and you should be good to go!

Solution 2:

You can fadeIn() the next image in the callback of fadeOut() as shown below:

$(window).load(function() {
  var $slider = $("#backgroundChanger"),
    $slides = $slider.find("img"),
    $firstSlide = $slides.first();

  functioncycleImages() {
    var $active = $('#backgroundChanger .active'),
      $next = ($active.next().length > 0) ? $active.next() : $firstSlide;
    $active.fadeOut(1000, function() {
      $active.removeClass('active');
      $next.fadeIn(1000).addClass('active');
    });
  }

  setInterval(cycleImages, 3000);
})
#backgroundChangerimg {
  position: absolute;
  width: 150px;
  height: 100px;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="backgroundChanger"><imgclass="active"src="http://i46.tinypic.com/2epim8j.jpg" /><imgsrc="http://i49.tinypic.com/28vepvr.jpg" /><imgsrc="http://i50.tinypic.com/f0ud01.jpg" /></div>

Notes:

  • Since we're dealing with images, It's better to use load() handler than ready() to make sure the slide show starts after the images are loaded
  • You can slightly improve the performance by caching the elements accessed frequently
  • You don't have to play with z-index property at all since both fadeIn() and fadeOut() changes the elements `display property itself

Post a Comment for "Fadein() Images In Slideshow Using Jquery"