Skip to main content

How to use the Youtube JS API to play music in the background

The Youtube JavaScript API allows you to embed YouTube videos and interact with them programatically. To use it, first you need to embed this script into your page:

<script src=""></script>.

If you just want the audio, you can hide the element that contains the video:

<div id="player" style="position: absolute; top: -9999px; left: -9999px;"></div>

Here we use absolute positioning with negative coordinates because using display: none; will prevent the onReady handler from the Youtube player from triggering on Firefox. I ran across this problem when making this.

Finally, here's a full example that will wait for the video to load and automatically play it: