1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Using JS to play random on click - would like to randomize

Discussion in 'JavaScript' started by jazzylee77, Dec 25, 2008.

  1. #1
    I'm doing something funny on a page. I've got it so when you click a link it plays a sound.
    SEMrush
    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>
    Code (markup):
    a dummy span on the page
    <span id="dummy"></span>
    Code (markup):
    and this to call it
    <a href="#" onclick="playSound('path to soundfile');">Click here</a>
    Code (markup):
    So far so good. Now I would like to make play a random sound.
     
    jazzylee77, Dec 25, 2008 IP
    SEMrush
  2. phper

    phper Active Member

    Messages:
    247
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    60
    #2
    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]);
    }
    Code (markup):
    And change your onclick event to call playRandom().
     
    phper, Dec 28, 2008 IP
  3. jazzylee77

    jazzylee77 Peon

    Messages:
    578
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    0
    #3
    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 29, 2008 IP
  4. jazzylee77

    jazzylee77 Peon

    Messages:
    578
    Likes Received:
    36
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Don't I need to change +soundfile+ to something here?
     
    jazzylee77, Dec 29, 2008 IP