The HTML loop attribute specifies that the media file will play repeatedly from the beginning once it has finished.
Definition and Usage
➔ If the loop attribute is used with the <audio> and <video> elements, the media will automatically restart until it is stopped.
➔ It is recommended to use the muted attribute together when using the autoplay or loop attribute on the <audio>, <video> elements.
➔ The loop attribute is boolean, and the values loop="loop", loop="true", or just loop have the same effect.
Syntax
//In HTML
<video controls id="myvideo" loop>
<source src="video-source.mp4" type="video/mp4">
This browser does not support the video tag.
</video>
//In JavaScript
<script>
const element = document.getElementById('myvideo');
element.loop = true;
element.setAttribute('loop', 'false');
</script>
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML loop attribute example</title>
<style>
.mydiv {
border: 2px solid black;
padding: 30px;
background: rgb(100, 100, 100, 0.3);
}
input[type='submit'] {
width: 120px;
margin: 10px 0px;
padding: 10px 20px;
border-radius: 5px;
background-color: #000;
color: white;
text-align: center;
}
input[type='submit']:hover {
background-color: #f6f6f6;
color: #000;
}
</style>
</head>
<body>
<div id="sample" class="mydiv">
<h3>HTML loop attribute example</h3>
<p>The loop attribute specify that the media file will restarted once it has finished.</p>
<!-- "https://mdn.github.io/learning-area/html/multimedia-and-embedding/video-and-audio-content/rabbit320.mp4" -->
<video controls id="myvideo" loop>
<source src="source-video.mp4" type="video/mp4">
This browser does not support the video tag.
</video><br><br>
<input id="loop" type="submit" value="Stop loop" onclick="toggleLoop()">
<input id="play" type="submit" value="Play" onclick="playpause()">
<input type="submit" value="Stop" onclick="videoStop()">
</div>
</body>
<script>
let myvideo = document.getElementById("myvideo");
let buttonLoop = document.getElementById("loop");
let buttonPlay = document.getElementById("play");
function toggleLoop() {
if (myvideo.loop) {
myvideo.loop = false;
buttonLoop.value = "Loop Stoped";
} else {
myvideo.loop = true;
buttonLoop.value = "Loop Running";
}
}
function playpause() {
if (myvideo.paused) {
myvideo.play();
buttonPlay.value = "Pause"
} else if (myvideo.play) {
myvideo.pause();
buttonPlay.value = "Play";
}
}
function videoStop() {
myvideo.pause();
myvideo.currentTime = 0;
buttonPlay.value = "Play";
}
</script>
</html>
Click on the "Try it Now" button to see how it works.