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.
The property returns true when the loop attribute is present and false otherwise. Assigning a boolean adds or removes the attribute.
Syntax
// Get the value
let repeating = mediaElement.loop;
// Set the value
mediaElement.loop = true;Example
This runnable page toggles looping on an audio clip and reports the current state. With loop on, the clip restarts forever; with it off, playback stops at the end.
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>loop Demo</title></head>
<body>
<h2>Repeat an audio clip</h2>
<audio id="myAudio" controls>
<source src="https://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
</audio>
<p><button onclick="toggleLoop()">Toggle loop</button></p>
<p id="output">Looping: false</p>
<script>
const audio = document.getElementById("myAudio");
const out = document.getElementById("output");
function toggleLoop() {
audio.loop = !audio.loop;
out.textContent = "Looping: " + audio.loop;
}
</script>
</body>
</html>More Examples
For a silent background video, combine loop with muted and autoplay so the browser permits it to start on its own and repeat forever.
<!DOCTYPE html>
<html>
<body>
<video id="bg" width="320" loop muted autoplay controls>
<source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
</video>
<p id="msg"></p>
<script>
const bg = document.getElementById("bg");
// ended never fires while looping, so this stays silent
bg.addEventListener("ended", () => {
document.getElementById("msg").textContent = "ended fired";
});
document.getElementById("msg").textContent = "loop = " + bg.loop;
</script>
</body>
</html>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.
Key Takeaways
- loop is a boolean reflecting the loop HTML attribute.
- true makes the media restart automatically when it reaches the end.
- false lets playback stop at the end and fires the ended event.
- While looping, ended never fires because the media never truly ends.
- Pair loop with muted + autoplay for background/hero videos.
