Articles directory - Debt Consolidation - Debt Consolidation - Wordpress Theme - Find jobs

PDA

View Full Version : Using JS to play random on click - would like to randomize


jazzylee77
Dec 25th 2008, 7:14 pm
I'm doing something funny on a page. I've got it so when you click a link it plays a sound.

Using this code in the head

<script language="javascript" type="text/javascript">
function playSound(soundfile) {
document.getElementById("dummy").innerHTML=
"<embed src=\""+soundfile+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
}
</script>

a dummy span on the page <span id="dummy"></span>

and this to call it <a href="#" onclick="playSound('path to soundfile');">Click here</a>

So far so good. Now I would like to make play a random sound.

phper
Dec 28th 2008, 9:49 pm
Put the file paths in an array, generate a random number that points to an index in the array and play that.

var paths = new Array('path1', 'path2', 'path3');
function playRandom ()
{
var index = Math.floor(Math.random() * paths.length);
playSound(paths[index]);
}

And change your onclick event to call playRandom().

jazzylee77
Dec 29th 2008, 8:16 am
Thanks I knew it would be something like that. I'll pm a link when it is working later. It's kinda funny. :)

jazzylee77
Dec 29th 2008, 8:53 am
Don't I need to change +soundfile+ to something here?

"<embed src=\""+soundfile+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";