Using Javascript for iFrame src URL

1.4k Views Asked by At

I'm playing around with the YouTube API and JavaScript and I can't get this to work. I'm trying to use JavaScript to give the video URL to the iFrame. This is what I have in the body of my HTML page:

<iframe id="ytplayer" type="text/html" width="720" height="405" src="" frameborder="0" allowfullscreen>

<script type="text/javascript">
    document.getElementById("ytplayer").src = "https://www.youtube.com/embed/0rhwc5_iWkA?autoplay=1";
</script>

It's just a trivial example but I can't get the video player to appear. I've looked at various ways to achieve the same result but nothing works. What's going wrong?

1

There are 1 best solutions below

1
On BEST ANSWER

You need to close your iframe.

<!DOCTYPE HTML>
<html>
<body>
    <iframe id="ytplayer" type="text/html" width="720" height="405" src="" frameborder="0" allowfullscreen></iframe>
    <script type="text/javascript">
        document.getElementById("ytplayer").src = "https://www.youtube.com/embed/0rhwc5_iWkA?autoplay=1";
    </script>
</body>
</html>