How to embed YouTube autoplay video on mobile with JavaScript?

To embed YouTube autoplay video on mobile with JavaScript, we use the YT.Player constructor.

For instance, we write

const createYoutubePlayer = () => {
  const youtubePlayer = new YT.Player("youtubePlayer", {
    videoId: "YOURID",
    width: 277,
    height: 600,
    playerVars: {
      autoplay: 1,
      controls: 0,
      showinfo: 1,
      modestbranding: 1,
      loop: 1,
      fs: 0,
      cc_load_policy: 0,
      iv_load_policy: 3,
      autohide: 1,
      playsinline: 1,
    },
    events: {
      onReady: (e) => {
        e.target.mute();
      },
      onStateChange: (e) => {
        this.onPlayerStateChange(e);
      },
    },
  });
};

to create a new YT.Player instance. with the ID of the video container element.

And then we set some options.

We add autoplay on load with

autoplay: 1

We hide the controls with controls: 0.

We hide the video title with showinfo: 1.

modestbranding: 1 hides the YouTube branding.

loop: 1 makes the video loop.