To embed a YouTube video in an HTML page, you can use the YouTube embed code or the YouTube iframe API. Here are the steps for each method:
- YouTube Embed Code:
- Visit the YouTube video page and click on the “Share” button below the video.
- Click on the “Embed” option to get the embed code.
- Copy the provided HTML code snippet.
<iframe width="560" height="315" src="https://www.youtube.com/embed/VIDEO_ID" frameborder="0" allowfullscreen></iframe>
- Replace
VIDEO_ID
with the actual ID of the YouTube video you want to embed. Example usage:
<iframe width="560" height="315" src="https://www.youtube.com/embed/dQw4w9WgXcQ" frameborder="0" allowfullscreen></iframe>
In this example, the YouTube video with the ID “dQw4w9WgXcQ” is embedded with a width of 560 pixels and a height of 315 pixels.
- YouTube Iframe API:
Include the YouTube iframe API script in your HTML file. <script src="https://www.youtube.com/iframe_api"></script>
Create a container element (e.g., a <div>
) where you want to embed the video. <div id="player"></div>
<script> // This function creates an <iframe> player and loads the YouTube video function onYouTubeIframeAPIReady() { new YT.Player('player', { videoId: 'VIDEO_ID', width: 560, height: 315, playerVars: { // Add any desired player parameters here }, }); } </script>
Add JavaScript code to create and control the YouTube player using the API.
Replace VIDEO_ID
with the actual ID of the YouTube video you want to embed. Example usage:
<script>
function onYouTubeIframeAPIReady() {
new YT.Player('player', {
videoId: 'dQw4w9WgXcQ',
width: 560,
height: 315,
playerVars: {
// Add any desired player parameters here
},
});
}
</script>
In this example, the YouTube video with the ID “dQw4w9WgXcQ” is embedded in the element with the ID “player” using the YouTube iframe API.
Both methods allow you to embed YouTube videos in your HTML page, and you can customize the dimensions, player parameters, and appearance based on your requirements. The YouTube iframe API provides more control and functionality, such as handling events and dynamically controlling the player.