Manoj Soni Manoj Soni - 4 months ago 36
jQuery Question

Fade in and Fade Out Text in DIV - Remove Loop

I have created a DIV with 3 different quotes fade in and fade out.

I am using below jQuery code for the same.

(function() {
var quotes = $(".changetxt");
var quoteIndex = -1;
function showNextQuote() {
++quoteIndex;
quotes.eq(quoteIndex % quotes.length)
.fadeIn(1000)
.delay(4000)
.fadeOut(500, showNextQuote);
}
showNextQuote();
})();


HTML CODE

<div class="toptext">
<div class="changetxt">
”The simple act of paying positive attention to<br>
people has a great deal to do with productivity”
<p>- Tom Peters</p>
</div>

<div class="changetxt">
”If you deprive yourself of outsourcing and your competitors<br> do not, you are putting yourself out of business”
<p>- Lee Kuan Yew</p>
</div>

<div class="changetxt">
”Focus on being PRODUCTIVE<br>
instead of busy”
<p>- Tim Ferris</p>
</div>
</div>


It is working perfect but I don't want to loop, There are 3 quotes, so as soon as it shows last (third) quote it should stop animation and no loop.

How can I achieve this?

Answer

Check if quoteIndex is in the third execution. If it is, then return

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

    function showNextQuote() {
        if (quoteIndex == 2) {
            return;
        }
        ++quoteIndex;
        quotes.eq(quoteIndex % quotes.length)
            .fadeIn(1000)
            .delay(4000)
            .fadeOut(500, showNextQuote);
    }
    showNextQuote();
})();

Update

To have the last quote stay, you can use a different approach in which you conditionally call fadOut

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

    function showNextQuote() {
        ++quoteIndex;
        quotes.eq(quoteIndex % quotes.length)
            .fadeIn(1000)
            .delay(4000);
        if(quoteIndex < 2){
            quotes.eq(quoteIndex % quotes.length).fadeOut(500, showNextQuote);
        }
    }
    showNextQuote();
})();