Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Jan 2005
    Location
    England
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Thumbs down Selecting random data from an array

    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:
    Code:
    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.
    Congratulations on discovering the hidden sig! Click here to claim your prize!

  • #2
    teh Moderatorinator
    Join Date
    Sep 2004
    Location
    USA
    Posts
    2,472
    Thanks
    4
    Thanked 40 Times in 40 Posts
    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:
    Code:
    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>
    Last edited by Brandoe85; 02-03-2005 at 07:35 AM.

  • #3
    New Coder
    Join Date
    Jan 2005
    Location
    England
    Posts
    13
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Angry Um...

    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:
    Code:
    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?
    Congratulations on discovering the hidden sig! Click here to claim your prize!

  • #4
    New Coder
    Join Date
    Jan 2005
    Location
    Atlanta
    Posts
    24
    Thanks
    0
    Thanked 0 Times in 0 Posts
    JavaScript is case sensitive. getElementById rather than getelementbyid.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •