0

I'm using this on a password-protected site, so I can't share with you a URL. I'm trying to use document.write to white some HTML inside a JS call that's designed to display a different YouTube video based on the time of day. It was working with just text, but not with anything else, it seems. I've tried a number of different methods, none of which seems to work. Here's what I'm doing:

<script type="text/javascript" language="JavaScript">
var myDate = new Date();
/* hour is before noon */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 18 )
{
    document.write('<iframe width=\"100%\" height=\"340px\" src=\"http://youtu.be/MswheXWqlbQ\" frameborder=\"0\" allowfullscreen></iframe>');
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
    document.write('<iframe width=\"100%\" height=\"340px\" src=\"//www.youtube.com/embed/MswheXWqlbQ\" frameborder=\"0\" allowfullscreen></iframe>');
}
</script>
Adam Bell
  • 819
  • 1
  • 10
  • 38
  • 2
    You might want to take a look at [Why is document.write considered a “bad practice”?](http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice) – Qantas 94 Heavy Dec 07 '14 at 01:30
  • Although not relevant, you don't need to escape double quotes when the string is quoted with single quotes. – outlyer Dec 07 '14 at 01:44
  • Yea, i figured innerHTML is probably a better way to go than document.write last night. – Adam Bell Dec 07 '14 at 17:56

2 Answers2

1

Use the official YouTube embed URLs:

http://youtube.com/embed/VIDEO_ID instead of youtu.be which is causing a cross site request error.

Œlrim
  • 527
  • 2
  • 10
0

Thanks for the suggestions. I found an innerHTML script and I tried it and it seems to have worked fine.

Here's my new script:

<script>
function dynamicYT(){

    var d  = new Date();
    var h = d.getHours();

if ((h>=0 && h<=5) || (h>=18 && h<= 23))
{
    document.getElementById("bgText").innerHTML='<iframe width="560" height="315" src="http://youtube.com/embed/MswheXWqlbQ" frameborder="0" allowfullscreen></iframe>';
} else {
    document.getElementById("bgText").innerHTML='<iframe width="420" height="315" src="http://youtube.com/embed/PKrzVIOvvQU" frameborder="0" allowfullscreen></iframe>';
}
}
window.onload = dynamicYT;
</script>
Adam Bell
  • 819
  • 1
  • 10
  • 38