Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Video.js Player Fails To Play After Dispose And Re-Initialize

I'm trying to use the video.js player in a modal popup. I'm initializing the player when the modal loads and disposing it when the modal is closed. It works fine the first time but when I try to open the popup again and re-initialize the player, it does not play with errors in the console.

Here's my code:

<a href="#openModal" id="open_modal_button">Open Modal</a>
<div id="openModal" class="modalDialog">
    <div>
        <a href="#close" title="Close" class="close" id="close_modal_button">X</a>
        <div id='videoDiv'> </div>
    </div>
</div>

<script type="text/javascript">
open_modal_button.addEventListener("click", function() {
    var videoDiv = document.getElementById('videoDiv');
    var video = createVideoElement('vid1');
    addSource(video, "http://foo.mp4");
    videoDiv.appendChild(video);
    videojs('vid1', {}, function() {})
});

close_modal_button.addEventListener("click", function(e) {
    var player = videojs('vid1');
    player.dispose();
});
</script>

I get these error messages in the browser console when I launch the modal for the second time:

Uncaught TypeError: window.videojs[componentClass] is not a function    video.debug.js
Uncaught TypeError: Cannot read property 'className' of null            video.debug.js
like image 370
Harsha Bhat Avatar asked Oct 27 '25 15:10

Harsha Bhat


1 Answers

This is along the lines of what you're doing and works without error.

<button id="add">Add player</button>
<button id="remove" disabled>Remove player</button>
<div id="videoDiv"></div>

<script type="text/javascript">
  var open_modal_button = document.getElementById('add');
  var close_modal_button = document.getElementById('remove');

  open_modal_button.addEventListener("click", function() {
    var videoDiv = document.getElementById('videoDiv');
    var video = document.createElement('video');
    var source = document.createElement('source');
    video.id = 'vid1';
    video.className = 'video-js vjs-default-skin';
    video.setAttribute('controls', 'controls');
    source.setAttribute('src', 'http://vjs.zencdn.net/v/oceans.mp4');
    source.setAttribute('type', 'video/mp4');
    video.appendChild(source);
    videoDiv.appendChild(video);
    videojs('vid1', {}, function() {});
    close_modal_button.removeAttribute('disabled');
    open_modal_button.setAttribute('disabled', true);
  });

  close_modal_button.addEventListener("click", function(e) {
    var player = videojs('vid1');
    player.dispose();
    open_modal_button.removeAttribute('disabled');
    close_modal_button.setAttribute('disabled', true);
  });
</script>

Example: http://output.jsbin.com/ciqoji

like image 90
misterben Avatar answered Oct 30 '25 08:10

misterben



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!