Ways to embed and play Youtube video in HTML

Ways to embed and play Youtube video in HTML
Ways to embed and play Youtube video in HTML

I will in this article go over two different examples of how to embed youtube videos on an HTML page.

The following two are:

  1. Embed element
  2. Iframe Element

Embed Youtube videos using embed element in HTML

This HTML Markup comprises an HTML TextBox, a Button, and an Embed Component.

We have appointed a jQuery click event handler. So when the button is clicked, the youtube video is fetched, and the video will play, as it is extracted from the Youtube Video ID.

<input type="text" id="txtUrl" style="width: 300px" />
<input type="button" id="btnPlay" value="Play" />
<hr />
<embed id="video" src="" wmode="transparent" type="application/x-shockwave-flash"
    width="420" height="315" allowfullscreen="true" title="Adobe Flash Player"></embed>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $("body").on("click", "#btnPlay", function () {
        var url = $("#txtUrl").val();
        url = url.split('v=')[1];
        $("#video")[0].src = "https://www.youtube.com/watch?v=mXLxMXvDXSs&t=6s&ab_channel=Silsen" + url;
    });
</script>

Embed Youtube videos using Iframe element in HTML

This contains roughly the same, with one exception, the Iframe element.

<input type="text" id="txtUrl" style="width: 300px" />
<input type="button" id="btnPlay" value="Play" />
<hr />
<iframe id="video" width="420" height="315" frameborder="0" style="display: none"
    allowfullscreen></iframe>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $("body").on("click", "#btnPlay", function () {
        var url = $("#txtUrl").val();
        url = url.split('v=')[1];
        $("#video")[0].src = "https://www.youtube.com/watch?v=mXLxMXvDXSs&t=6s&ab_channel=Silsen" + url;
        $("#video").show();
    });
</script>