HTML Audio & Video
HTML DOM Audio loop Property
The loop property sets or returns whether a media element should start over again, every time it reaches the end. It reflects the loop HTML attribute and is a boolean.
Definition and Usage
When loop is true, the browser automatically seeks back to the start and continues playing as soon as the media finishes, repeating indefinitely. When it is false, playback stops at the end and the ended event fires.
Syntax
// Get the value
let repeating = mediaElement.loop;
// Set the value
mediaElement.loop = true;The property returns true when the loop attribute is present and false otherwise. Assigning a boolean adds or removes the attribute.
Example
<audio id="myAudio" controls>
<source src="song.mp3" type="audio/mpeg">
</audio>
<button onclick="toggleLoop()">Toggle loop</button>
<script>
const audio = document.getElementById("myAudio");
function toggleLoop() {
audio.loop = !audio.loop;
console.log("Looping:", audio.loop);
}
</script>Looping is ideal for background music or ambient video. Because a looping element never reaches a true end, the ended event never fires while loop is enabled.
Combine loop with muted and autoplay for background videos, since browsers allow muted looping video to autoplay but block looping audio that plays out loud without user interaction.
