...

View Full Version : Selecting random data from an array



AlterEgo
02-02-2005, 10:26 PM
I have an array, variable name "lyrics". What I'm trying to do is display a random lyric every time the user visits the page. I'm using this script:

var line = lyrics.length;
var whichline=Math.round(Math.random()*(line - 1));
function showlyric(){document.write(lyrics[whichline]);}
showlyric();}
But this always shows just the first lyric in the array, even after refreshing. Also, the lyric is the only thing that shows on the page, even though I have the script inside the table cell that I want it in. So basically it's just a big horrible mess and so I was wondering if someone would be able to point me in the right direction? Thanks.

Brandoe85
02-03-2005, 07:32 AM
Your function should work, and the reason it's only showing the lyric is because your using document.write(), try using a div tag or something along those lines:


var line = lyrics.length;
var whichline=Math.round(Math.random()*(line - 1));

function showlyric()
{
document.getElementById('lyric').innerHTML=(lyrics[whichline]);
}
window.onload = function(){ showlyric();};
.....
then add a div tag in your document body
<div id="lyric">
</div>

AlterEgo
02-04-2005, 05:50 PM
Thanks for your help, but my HTML editor still shows a problem with the getelementbyid line. I've got this, from what you told me:

var lyrics = new Array (lyrics here)
var line = lyrics.length;
var whichline=Math.round(Math.random()*(line - 1));
function showlyric(){
document.getelementbyid('lyric').innerHTML=(lyrics[whichline])}
Then <body onload="showlyric();"> in the body tag, and <div id="lyric"></div> in the body itself.
What have I done wrong with this line?

jmccaskill
02-04-2005, 06:08 PM
JavaScript is case sensitive. getElementById rather than getelementbyid.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum