John
John

Reputation: 1009

creating own jQuery content slider / fade

I don't want to use a plugin but am new to jQuery - I have the following HTML:

<div class="slide">
    <a href="http://www.mysite.co.uk"><img src="images/img.jpg" width="920" height="360" /></a>
    </div>

<div class="slide">
    <a href="http://www.mysite.co.uk"><img src="images/img.jpg" width="920" height="360" /></a>
    </div>

<div class="slide">
    <a href="http://www.mysite.co.uk"><img src="images/img.jpg" width="920" height="360" /></a>
    </div>

I have used jQuery to hide all but the first "slide" :

$('.slide:first').siblings().css('display', 'none');

What I now want to do is auto advance through the slide divs, so hide the first div.slide and show the second then hide that to show the third and repeat. I have looked at the fade toggle functions but am a bit lost?

Thanks, John

Upvotes: 0

Views: 857

Answers (1)

lucuma
lucuma

Reputation: 18339

This should help you out a little bit. What it basically does is:

  1. Hide all but first slide element.
  2. In the function that is called you want to hide the currently shown element and show the next one.. It is quite simple:

Here is a jsfiddle: http://jsfiddle.net/lucuma/CXsdP/4/

function doSlides() {

        var imgIndex = $('#slideshow div:visible').index();

        var imgNext = (imgIndex + 1) % $('#slideshow div').length;

        $('#slideshow div:visible').fadeOut(500);

        $('#slideshow div').eq(imgNext).fadeIn(500);
    }
    $('#slideshow div:gt(0)').hide();

    setInterval(doSlides, 1000);

Here is an alternate way to do it:

function doSlides() {
    var $imgIndex = $('#slideshow div:visible');

    var $next = $imgIndex.next();

    if ($next.length==0) {
        $next = $('#slideshow >:first-child');   // loop back to first 
    }
    $imgIndex.fadeOut(500);  
    $next.fadeIn(500);
}

$('#slideshow div:gt(0)').hide();

setInterval(doSlides, 1000);

​ ​

Upvotes: 2

Related Questions