javascriptjqueryimagecyclecross-fade

jQuery Image Crossfade not working


Hello what is wrong with our jQuery image crossfade set-up!? http://tips.techmatemn.com/

HTML

<div class="hero-cycler">
    <img class="active" alt="Tips qualified Client 1" src="<?php bloginfo('stylesheet_directory'); ?>/assets/img/hero-bk-1.jpg">
    <img alt="Tips qualified Client 2" src="<?php bloginfo('stylesheet_directory'); ?>/assets/img/hero-bk-2.jpg">
</div>

CSS

.hero-cycler{position:relative;}
.hero-cycler img{position:absolute;z-index:1}
.hero-cycler img.active{z-index:3}

SCRIPT

<script> // homepage client images
function cycleImages(){
      var $active = $('.hero-cycler .active');
      var $next = ($active.next().length > 0) ? $active.next() : $('.hero-cycler img:first');
      $next.css('z-index',2);//move the next image up the pile
      $active.fadeOut(1500,function(){//fade out the top image
      $active.css('z-index',1).show().removeClass('active');//reset the z-index and unhide the image
          $next.css('z-index',3).addClass('active');//make the next image the top one
      });
    }

$(document).ready(function(){
// run every 7s
setInterval('cycleImages()', 7000);
})
</script>

Thanks!


Solution

  • Change the way you call the function. Your setInterval uses the string parameter which is depreciated and generally not recommended. Use the standard method shown below to correctly run the function.

    Change setInterval('cycleImages()', 7000); to setInterval(cycleImages, 7000);

    Full working copy with generic filler images:

    function cycleImages() {
      var $active = $('.hero-cycler .active');
      var $next = ($active.next().length > 0) ? $active.next() : $('.hero-cycler img:first');
      $next.css('z-index', 2); //move the next image up the pile
      $active.fadeOut(1500, function() { //fade out the top image
        $active.css('z-index', 1).show().removeClass('active'); //reset the z-index and unhide the image
        $next.css('z-index', 3).addClass('active'); //make the next image the top one
      });
    }
    
    $(document).ready(function() {
      // run every 7s
      setInterval(cycleImages, 7000);
    })
    .hero-cycler {
      position: relative;
    }
    .hero-cycler img {
      position: absolute;
      z-index: 1
    }
    .hero-cycler img.active {
      z-index: 3
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="hero-cycler">
      <img class="active" alt="Tips qualified Client 1" src="https://unsplash.it/300/200/?image=0">
      <img alt="Tips qualified Client 2" src="https://unsplash.it/300/200/?image=1">
    </div>

    (A quick check of the browser console would have shown you the error: Uncaught ReferenceError: cycleImages is not defined which would have been very helpful to include in your question)