views:

35

answers:

1

Hi,

I'm new to Jquery and even Javascript. Found and implemented this script that in a timely matter replaces images. Script works well when I wrap the images in an tag. I want the images to be links. As soon as I wrap the tags in an tag the script sill refreshes every so many seconds but it doesn't load the next image.

What should I change in this script to have the next image load correctly

<script type='text/javascript'>
    function swapImages(){
      var $active = $('#rooster .active');
      var $next = ($('#rooster .active').next().length > 0) ? $('#rooster .active').next() : $('#rooster img:first');
      $active.fadeOut(function(){
      $active.removeClass('active');
      $next.fadeIn().addClass('active');
      });
    }

    $(document).ready(function(){
      // Run our swapImages() function every 5secs
      setInterval('swapImages()', 5000);
    }); </script>
A: 

The problem is here:

$('#rooster img:first')

It's trying to find the first <img> and fade it in, but since it's wrapped in a tag it won't be doing much good, you need to change the tag type there, like this

$('#rooster a:first')

Overall there are some more changes though, for example you should never pass a string to setInterval() if you can avoid it, instead just pass the function name, like this:

setInterval(swapImages, 5000);

Once you do this, you don't have to leave the function as a global one, you can tidy it up in your document.ready, overall you could do something like this:

$(function(){
  function swapImages(){
    var $active = $('#rooster .active');
    var $next = $active.next().length > 0 ? $active.next() : $('#rooster a:first');
    $active.fadeOut(function(){
      $active.removeClass('active');
      $next.fadeIn().addClass('active');
    });
  }
  setInterval(swapImages, 5000);
});
Nick Craver