Click above to generate more lyrics...
|
<span id="words" name="words">
</span>
<form action="javascript:lyrics()">
<input type="submit" value="Next verse"> </form>
Rock Lyric Engine is copy-lefted by Andy Deck
|
Rock Lyrics using Math.random() and Math.floor()
This example code demonstrates the use of an array of words which are
composed into an HTML fragment and then assigned to a <span> tag.
<script language="javascript" type="text/javascript">
var word = new Array("I", "you", "love", "hurt", "sad", "rock", "do",
"baby", "man", "car", "sex", "rockin", "smokin", "forever",
"ooo!", "uh-huh", "(Guitar solo)", "YEAH!", "can't", "road" );
function lyrics(){
var i, wrd, line = 5, song = " " ;
while(line>0){
wrd=5;
while(wrd>0){
i = Math.floor( Math.random() * word.length );
song = song + " " + word[i];
wrd--;
}
line--;
song = song + "<br><br>";
}
var words = document.getElementById('words');
words.innerHTML = song;
}
</script>
|
The Math.random() method delivers a random number between 0.0 and 1.0. In
order to map that random value to an index of our array, we multiply it by the
length of the array and drop the result to the nearest whole number using Math.floor().
Each individual word is concatenated onto the song variable before it is put into the
innerHTML property of the <span> tag.
|