Caleb Kester Caleb Kester - 2 years ago 93
HTML Question

Detect HTML Video Source Change Event (addEventListener)

I'm trying to find an event for when an HTML video changes it's source. I'm using mediaelement.js as my skin but I couldn't find any extra events that it had.

All of my searches just turns up instructions on how to change the source, not detect if the source was changed.

I'm hoping I can just do something like

.addEventListener('sourceChange', function (e) { })

but I can't seem to find if there's an actual event.


Answer Source

You can use loadedmetadata, loadeddata as well as canplay events to find out if a source has loaded and can be played. The event contains reference to the source video element in question and from there you can check if the url has changed compared to the previous one.

Example (proof of concept)

var cUrl = v.src;     // current url

v.onloadedmetadata = function() {
  if (this.src !== cUrl) {
    i.innerHTML = "<b>Source changed!</b>";
    cUrl = this.src;  // update, etc..
  else {
    i.innerHTML = "Source is playing... (changes source in 5 sec.)";
    setTimeout(function() {
      i.innerHTML = "Loading new source...";
      v.src = "";
    }, 5000);
<div id=i>Loading video, please wait...</div><br>
<video id=v autoplay muted controls

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download