Reputation: 276
so I am trying to rotate some text snippets sequentially with javascript. The below code does it randomly, and my javascript is zilch. Can someone direct me in how to make this rotation sequential? Thanks!
Site is built in Concrete5. http://www.travelus.com.au/about-us/trial
<head>
<script type="text/javascript">
//messages keep each message on one line
var messages=new Array(
'message 1',
'message 2',
'message 3',
'message 4.'
)
//timer in seconds
var timer=5;
function firstMessage(){
newMessage()
setInterval ( "newMessage()", timer*1000 );
}
function newMessage()
{
var randno=Math.floor(Math.random()*(messages.length));
var elem =document.getElementById("msg");
elem.innerHTML = messages[randno];
}
</script>
</head>
<body onload="firstMessage()">
<div id="msg">There is supposed to be some content in this box, but you need Javascript to see it...</div>
</body>
Upvotes: 0
Views: 232
Reputation: 4809
Try this, variable i maintains index of current element to be displayed. And after it reaches end of messages, it resets back to 0.
var i=0;
function newMessage()
{
if(i===messages.length)
{
i=0;
}
var elem =document.getElementById("msg");
elem.innerHTML = messages[i];
i=i+1;
}
Upvotes: 1
Reputation: 257
Right now your message is selected at random with the randno
variable which randomly selects one of your messages by generating a random number. To make it sequential (and rotating, as I assume you would like it), you need to make a variable that is scoped higher than the newMessage
function--basically outside of the function call.
To do this, you'd want to do something like this:
var index = 0;
function newMessage()
{
index = (index + 1) % messages.length
var elem =document.getElementById("msg");
elem.innerHTML = messages[index];
}
The %
symbol is a modulus and gives you the remainder of the new value of index divided by the number of messages you have so your number will never be higher than the number of messages you have. This is called modular arithmetic or clock arithmetic.
Upvotes: 1
Reputation: 191819
elem.innerHTML = messages[0];
messages.push(messages.shift());
Upvotes: 0