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 it working.

Here is the code without any fadeIn():


<div id="backgroundChanger">
  <img class="active" src="background1.jpg"/>
  <img src="background2.jpg"/>  
  <img src="background3.jpg"/>  


#backgroundChanger img{
#backgroundChanger img.active{


function cycleImages(){
      var $active = $('#backgroundChanger .active');
      var $next = ($active.next().length > 0) ? $active.next() : $('#backgroundChanger img:first');

 setInterval('cycleImages()', 7000);



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() {

}, 3000);

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

#backgroundChanger img:first-child {
  display: block;

#backgroundChanger img {
  display: none;

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


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();

  function cycleImages() {
    var $active = $('#backgroundChanger .active'),
      $next = ($active.next().length > 0) ? $active.next() : $firstSlide;
    $active.fadeOut(1000, function() {

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


  • 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


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.