Search code examples
javascriptjqueryhtmlcssfadein

Fade in and out without the loop


Here's the code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<style>
.quotes {display: none;}​
</style>
</head>

<body>
<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();

})();
</script>
</body>
</html>

It works as intended, it's supposed to loop, but I'd like to get rid of the loop. If anyone can help it'd be greatly appreciated.

Edit: I would like it so once it gets to the second quote it doesn't fade out and stays there.


Solution

  • As you have commented you don't want to fade-out the last quote, I think just have an if condition to check if it's last quote, if it's don't say to fade-out.

    define your function showNextQuote like bellow

     function showNextQuote() {
            ++quoteIndex;
            if(quoteIndex==quotes.length-1){ //if it's the last quote
                quotes.eq(quoteIndex).fadeIn(2000); //jsut fad-in & return
                return;
            }
            quotes.eq(quoteIndex)
                .fadeIn(2000)
                .delay(2000)
                .fadeOut(2000, showNextQuote);
        }
    

    DEMO