Fading in and out with Click

35 views Asked by At

I would want the quotes to start fading in/out and get to the next one after just clicking the screen. The way it is now, the first quote starts before I get to that page and it's a bit confusing. It's a scrolling website.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
(function() {

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

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

    showNextQuote();

})();
</script>
2

There are 2 answers

0
Gary Storey On

If you want it to wait for a click then don't automatically run showNextQuote() on the last line. Add it into a click event:

$(document).on('click', showNextQuote );

To show the first automatically:

++quoteIndex;
quotes.eq(quoteIndex).fadeIn(2500);

Then it will require a click for the next one to start.

0
guest271314 On

Try substituting $(document).ready(fn) alias $(function() {}) for IIFE (function() {})() ; .fadeTo() for .fadeIn() and .fadeOut() ; assigning click event to $(window) with showNextQuote set as handler for click event

$(function() {

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

    function showNextQuote() {
        ++quoteIndex;
        quotes.eq(quoteIndex % quotes.length)
            .fadeTo(2500, 1)
            .delay(2200)
            .fadeTo(4500, 0);
    }

    $(window).on("click", showNextQuote);

});
body {
  width:400px;
  height:300px;
}

.quotes {
  opacity:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
click
<div class="quotes">a</div>
<div class="quotes">b</div>
<div class="quotes">c</div>
<div class="quotes">d</div>