YouTube videos can be embedded into a webpage using the HTML <iframe> element. By adding the autoplay=1 parameter to the video's embed URL, you can configure the video to start playing automatically whne the player loads.
Autoplay behaviour may vary depending on browser settings and playback policies. Muted playback is often more reliable when implementing autoplay.
Example
To autoplay a YouTube video, embed it using the <iframe> element and add autoplay=1 to the video URL. The following example demonstrates how to implement it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Autoplay YouTube Video</title>
</head>
<body>
<h2 style="color:green">Autoplay YouTube Video in HTML</h2>
<iframe
width="560"
height="315"
src="https://www.youtube.com/embed/RLiN0bbeTD8?autoplay=1&mute=1"
title="YouTube video player"
allow="autoplay; encrypted-media; picture-in-picture"
allowfullscreen>
</iframe>
</body>
</html>
- <iframe> : Embeds the YouTube video into the webpage.
- width & height: Set the dimensions of the video player to 560 × 315 pixels.
- src: Specifies the YouTube video URL.
- autoplay=1: Enables automatic playback when the player loads.
- mute=1: Mutes the video, which can improve autoplay compatibility across browsers.
- title: Provides an accessible description of the embedded video player.
- allow="autoplay; encrypted-media; picture-in-picture" : Allows the player to use autoplay and other supported features.
- allowfullscreen: Allows the video to open in full-screen mode.
Note:Â Autoplay may still be blocked by browser policies or settings, even when the correct parameters are used.