0

I am trying to load a random video on page load. This is some javascript that I threw together that I thought might work. I'm not that familiar with javascript, so there might be a much easier way to do this... Any ideas?

function random_video {

    var string1 = '<div class="span4"><h3 class="meet">Meet the Makers</h3><iframe width="100%" height="200" src="http://www.youtube.com/embed/Ig-DbfPoz3o" frameborder="0" allowfullscreen></iframe></div>';

    var string2 = '<div class="span4"><h3 class="meet">Meet the Makers</h3><iframe width="100%" height="200" src="http://www.youtube.com/embed/estPhyfBGho" frameborder="0" allowfullscreen=""></iframe></div>';

    var string3 = '<div class="span4"><h3 class="meet">Meet the Makers</h3><iframe width="100%" height="200" src="http://www.youtube.com/embed/6JL4hpnZklk" frameborder="0" allowfullscreen=""></iframe></div>';

    var number = Math.floor((Math.random()*3)+1);

    if ( number == 1) {
      document.write(string1);
    } else ( number == 2 ) {
        document.write(string2);
    } else ( number == 3 ) {
        document.write(string3);
    }

};

1 Answers1

5

Would be more generalizable and easier to add more videos if you use an Array:

var videos = [
    'Ig-DbfPoz3o',
    'estPhyfBGho',
    '6JL4hpnZklk'
];

var index=Math.floor(Math.random() * videos.length);
var html='<div class="span4"><h3 class="meet">Meet the Makers</h3><iframe width="100%" height="200" src="http://www.youtube.com/embed/' + videos[index] + '" frameborder="0" allowfullscreen></iframe></div>';
document.write(html);
ampersand
  • 4,264
  • 2
  • 24
  • 32
  • The randomization logic is off a little bit. It should just be `Math.floor(Math.random() * videos.length)`. This will give out random numbers that are 1 less than the length of the array which is perfect since the array length (in this example) is 3, but the index of the third entry is `2`. – pseudosavant Apr 09 '12 at 21:26
  • 2
    ew! `document.write()`! – Barrie Reader Oct 17 '13 at 13:27