So I have this code that modifies the contents of a div on refresh.
But I also want it to fade in and out a new random text over a set amount of time. I don't know where to start here's my original code:
HTML:
<div id="logo" class="container">
<h1>InsiderIndy</h1>
<p id="myQuote">Slogan</p>
</div>
JavaScript:
<script type="text/javascript">
var myQuotes = new Array();
myQuotes[0] = "Quote1";
myQuotes[1] = "Quote2";
myQuotes[2] = "Quote3"
myQuotes[3] = "Quote4"
myQuotes[4] = "Quote5"
myQuotes[5] = "Quote6"
var myRandom = Math.floor(Math.random()*myQuotes.length);
$('#myQuote').html(myQuotes[myRandom]);
</script>
Any ideas? Thanks! :)
Full working example with an adjustable function for fade speed, pause time between rotations, and start position. Also returns back to the beginning when it reaches the end:
EDIT: I read your question too quickly the first time and wrote a function for a sequential rotation. I've updated my answer to include two functions--one for a sequential rotation startSeq()
and a second for a random rotation startRandom()
.
function startSeq(i,iSpeed, iPause) {
$('#myQuote').html(myQuotes[i]);
$('#myQuote').fadeIn(iSpeed,function() {
setTimeout(function() {
$('#myQuote').fadeOut(iSpeed,function() {
setTimeout(function() {
if (i++ == myQuotes.length) i =0;
startSeq(i,iSpeed,iPause);
},iPause);
});
},iPause);
});
}
function startRandom(iSpeed, iPause) {
var i = Math.floor(Math.random()*myQuotes.length);
$('#myQuote').html(myQuotes[i]);
$('#myQuote').fadeIn(iSpeed,function() {
setTimeout(function() {
$('#myQuote').fadeOut(iSpeed,function() {
setTimeout(function() {
startRandom(iSpeed,iPause);
},iPause);
});
},iPause);
});
}
//startSeq(0,1000,1000);
startRandom(1000,1000);
Looks like jQuery, so...
(function quote() {
var myRandom = Math.floor(Math.random()*myQuotes.length);
$('#myQuote').delay(5000)
.fadeOut(500, function() {
$(this).text(myQuotes[myRandom])
.fadeIn(500, quote);
});
})();
You should probably take some time and study the jQuery docs
Using jQuery:
var refreshMillis = 10 * 1000; // 10 seconds.
setInterval(function() {
var myRandom = Math.floor(Math.random()*myQuotes.length)
, $myQuote = $('#myQuote');
$myQuote.fadeOut(function() {
$myQuote.html(myQuotes[myRandom]).fadeIn();
});
}, refreshMillis);
Here's a working jsFiddle .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.