JavaScript Looping Media Fragments

The native HTML5 Video Element loop attribute does not support looping over set media fragments so we will implement a JavaScript solution that uses the TimeUpdate Event Listener

by trentHarlem

HTML

<video id="myVideo" controls autoplay loop mute>
  <source src="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4#t=12,18">
</video>

JavaScript

var video = document.getElementById('myVideo');
var videoSource = video.getElementsByTagName('source')[0];
var videoSourceSrc = videoSource.src;
var mediaFragment = videoSourceSrc.substr(videoSourceSrc.indexOf("#")+1, videoSourceSrc.length);
var mediaFragmentBound1 = parseInt(mediaFragment.substr(mediaFragment.indexOf("=")+1, mediaFragment.indexOf(",")));
var mediaFragmentBound2 = parseInt(mediaFragment.substr(mediaFragment.indexOf(",")+1, mediaFragment.length));

video.addEventListener('timeupdate', function() {
	checkMediaFragmentBounds(video, mediaFragmentBound1, mediaFragmentBound2);
});

function checkMediaFragmentBounds(video, x,y) {
	if(video.currentTime > y) {
  	video.currentTime = x;
    video.play();
  }
}