I want to make an animation of text in a particular DIV.
I’m trying to explain it with a simple example:
var yourDiv = document.getElementById('yourDiv');
yourDiv.innerHTML = turnWords();
function turnWords(){
var fruits = ["banana", "peach", "apple"]
return fruits[0];
}
In this case, the word “banana” shows up in the DIV.
But now, every 500 miliseconds, the innerHTML of that DIV needs to get another fruit inside.
I thought about a setTimeOut function with a loop that goes infinitely through the elements of the fruits Array.
But whatever I try, it doesn’t work out. I guess I’m overlooking some javascript basics.
Can someone help me with this?
var yourDiv = document.getElementById('yourDiv');
yourDiv.innerHTML = setInterval(function(){turnWords(1)},500);
function turnWords(j){
var fruits = ["banana", "peach", "apple"]
return fruits[j];
}
Something like this above should return “Peach” every 500 miliseconds.
Instead, it returns a number: “2364661”.
If this worked, I could put the setInterval in some infinite loop that asks turnWords(0), turnWords(1), turnWords(2), turnWords(0), …
Something like this?
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Test</title>
<script type="text/javascript">
var yourDiv; // div to contain the text
var fruits = ["banana", "peach", "apple"];
var currentfruit = 0;
function turnWords(){
currentfruit = ++currentfruit % fruits.length;
yourDiv.innerHTML = fruits[currentfruit];
setTimeout(turnWords, 500);
}
window.onload = function() {
yourDiv = document.getElementById('yourDiv');
yourDiv.innerHTML = fruits[currentfruit];
turnWords();
}
</script>
</head>
<body>
<div id="yourDiv"></div>
</body>
</html>
I’ll just swap those first 2 lines in the turnWords() function so they correctly show fruits[0] first instead of fruits[1].
function turnWords(){
yourDiv.innerHTML = fruits[currentfruit];
currentfruit = ++currentfruit % fruits.length;
setTimeout(turnWords, 500);
}
Hmm, I see.
It’s much more simpler than I thought 