1 Replies - 365 Views - Last Post: 27 April 2012 - 07:03 AM

#1 Aefio  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 14
  • Joined: 13-September 11

Randomly Selecting Files?

Posted 27 April 2012 - 06:43 AM

Hi. I have a webpage in development and on a certain page I want the user to be able to play a select list of songs, either randomly chosen or manually chosen. I have the Manual part setup but how would I accomplish the random part? Is there some sort of tag for random generations?
Is This A Good Question/Topic? 0
  • +

Replies To: Randomly Selecting Files?

#2 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3039
  • View blog
  • Posts: 4,548
  • Joined: 08-June 10

Re: Randomly Selecting Files?

Posted 27 April 2012 - 07:03 AM

No. Adding behavior to a website is the job of Javascript. I don't know how your manual song list works, so I can't give you any pointed suggestions, but to give you an idea of how this works I'll show you have you would randomly show an image.

<!DOCTYPE html>
<html>
    <head>
        <title>Example</title>
        <meta charset="UTF-8"/>
        <script>
        // A list of all the images that can be shown.
        var files = [
            "file1.jpg",
            "file2.jpg",
            "file3.jpg"
        ];
        
        window.onload = function() {
            // Select one of the images at random.
            var rand = Math.floor(Math.random() * files.length);
            var selectedFile = files[rand];
            
            // Show the image on the page
            var imgElem = document.getElementById("theImage");
            imgElem.setAttribute("src", selectedFile);
        }
        </script>
    </head>
    <body>
        <h1>The image</h1>
        <img id="theImage" alt="The random image"/>
    </body>
</html>


There a random number is generated with the Math.random() function, which returns a float number between 0 and 1. Multiplying that with the number of files available and rounding it down will give you a random index somewhere inside the array.

Then it's just a matter of using that random index to fetch the file and set it on whatever element plays the song.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1