Web Analytics Made Easy -
StatCounter Please help with random link code - CodingForum

Announcement

Collapse
No announcement yet.

Please help with random link code

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Please help with random link code

    I am trying to create a button that will randomly take you to a website from a list I created. It works except for one problem: Every now and then it will go to an error page as it tries to go to a "undefined" page. Could you take a look at my code and see if you can find where my flaw is?

    <html>

    <head>
    <base href="http://www.angelfire.com/realm/angelicknight/projects/ezring.html">
    <script language="JavaScript">
    var members = new Array(3);
    members[0] = "http://www.abacusconnection.com";
    members[1] = "http://www.activeyears.com";
    members[2] = "http://www.axciom.com";

    function randomgo()
    {
    var a = Math.round(Math.random()*3)
    var i = a
    location.href = members[a]
    }
    </script>
    </head>

    <body>
    <form>
    <input type="button" name="random" value="Random" onclick="randomgo();">
    </form>
    </body>
    </html>
    The James Website:
    www.angelfire.com/realm/angelicknight

  • #2
    Use Math.floor instead of Math.round and instead of hardcoding the 3, you can specify the length of the array.

    var a = Math.floor(Math.random()*members.length);

    What happened in your original code was that the output was rounded up to 3, resulting to members[3] being obviously undefined. Using Math.floor chops off the decimal making 2.99 equal to 2 not 3.
    Glenn
    vBulletin Mods That Rock!

    Comment


    • #3
      Thanks, that fixed it!
      The James Website:
      www.angelfire.com/realm/angelicknight

      Comment

      Working...
      X