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?
Randomly Selecting Files?
Page 1 of 11 Replies - 365 Views - Last Post: 27 April 2012 - 07:03 AM
Replies To: Randomly Selecting Files?
#2
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.
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.
<!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.
Page 1 of 1
|
|

New Topic/Question
Reply


MultiQuote




|