Alin
Alin

Reputation: 1228

Add next/prev button to text 'slider'

I have the following text 'slider' ( jsFiddle ) and I would like to add next / prev buttons to it and I don't quite know where to start..

I tried binding showNextQuote(); to a click function but what it did is show the two quotes simultaneously.

<h2 class="quotes">first quote</h2>
<h2 class="quotes">second quote</h2>

Script:

(function() {

    var quotes = $(".quotes");
    var quoteIndex = -1;

    function showNextQuote() {
        ++quoteIndex;
        quotes.eq(quoteIndex % quotes.length)
            .fadeIn(2000)
            .delay(2000)
            .fadeOut(2000, showNextQuote);
    }

    showNextQuote();

})();

PS: I also tried:

    $('#next').on('click', getNext);
    $('#prev').on('click', getPrev);

function getNext() {
    var $curr = $('.quotes:visible'),
        $next = ($curr.next().length) ? $curr.next() : $('.quotes').first();

    transition($curr, $next);
}

function getPrev() {
    var $curr = $('.quotes:visible'),
        $next = ($curr.prev().length) ? $curr.prev() : $('.quotes').last();
    transition($curr, $next);
}

Upvotes: 1

Views: 762

Answers (1)

Regent
Regent

Reputation: 5178

I suggest to use .stop() to stop current animation before running new one and passing 1 or -1 to function:

Fiddle.

HTML:

<h2 class="quotes">first quote</h2>
<h2 class="quotes">second quote</h2>
<h2 class="quotes">third quote</h2>
<input id="prev" type="button" value="Prev" />
<input id="next" type="button" value="Next" />

JS:

$(function()
{
    var quotes = $(".quotes");
    var quoteIndex = -1;

    function showQuote(change)
    {
        quoteIndex += change;
        if (quoteIndex < 0)
        {
            quoteIndex += quotes.length;
        }
        else if (quoteIndex >= quotes.length)
        {
            quoteIndex -= quotes.length;
        }
        quotes.stop(true, true).hide().eq(quoteIndex)
            .fadeIn(2000)
            .delay(2000)
            .fadeOut(2000)
            .queue(function() { showQuote(1); });
    }  
    showQuote(1);

    $('#prev').on('click', function()
    {
        showQuote(-1);
    });

    $('#next').on('click', function()
    {
        showQuote(1);
    });
});

Upvotes: 1

Related Questions