Michael
Michael

Reputation: 29

Simple cycled slideshow with next/prev link

I am more or less a beginner to Jquery and to start with it I tried to make a clickable, cycled slideshow, based on this one. So far so good. The code works (see below). My questions:

  1. Isn't there an easier way to write the code. I am kind of repeating the same code for prev and next.

  2. When I click on the next/prev links and the animation starts — and during the animation I click again, then sometimes the image is flickering or there is an error. Is there a way to force the animation to finish, before it reacts on my click.

Javascript:

    $(function() {

    $('#prev').click(function() {
        var $active = $('#slideshow IMG.active');
        var $prev = $active.prev();
        $active.addClass('last-active');

    if($active.is(":first-child")){$prev = $("IMG:last-child");}
        $prev.css({opacity: 0.0})
            .addClass('active')
            .animate({opacity: 1.0}, 1000, function() {
                $active.removeClass('active last-active');
            }); 

    }); 


    $('#next').click(function() {
        var $active = $('#slideshow IMG.active');
        var $next = $active.next();
        $active.addClass('last-active');

    if($active.is(":last-child")){$next = $("IMG:first-child");}
        $next.css({opacity: 0.0})
            .addClass('active')
            .animate({opacity: 1.0}, 1000, function() {
                $active.removeClass('active last-active');
            }); 

    }); 

    });

CSS:

    #slideshow {position:relative; height:350px; opacity:1.0;}
    #slideshow IMG {position:absolute; top:0; left:0; z-index:8; opacity:0.0;}
    #slideshow IMG.active {z-index:10; opacity:1.0;}
    #slideshow IMG.last-active {z-index:9;}
    #next {color:#0000ff; cursor:pointer;}
    #prev {color:#0000ff; cursor:pointer;}

HTML:

    <div id="slideshow">
        <img src="image1.jpg" class="active" />
        <img src="image2.jpg" />
        <img src="image3.jpg" />
        <img src="image4.jpg" />
    </div>
    <div id="next">NEXT</div>
    <div id="prev">PREV</div>

Upvotes: 2

Views: 2399

Answers (2)

XCS
XCS

Reputation: 28137

http://jsfiddle.net/kPD4n/

There you go.

1) Add the same class for "NEXT" and "PREV" buttons, and then check which is clicked.
2) Added .stop(0,1) to jump to end of animation.

Still a little buggy though...

Upvotes: 0

thomas
thomas

Reputation: 2578

Well everytime I come accross the need of building some cycle stuff, i utilize the jQuery Cycle PlugIn. This may not be the answer to you optimization question, but I think everyone should have taken a look at the Cycle plugin.

And as you can see here on the demo page you can make use of next/prev buttons very easy, too. Just like

$('#slideshow').cycle({ 
    fx:     'fade', 
    speed:  'fast', 
    timeout: 0, 
    next:   '#next', 
    prev:   '#prev' 
});

And your HTML code can stay that way.

Upvotes: 1

Related Questions