1

For an upcomming project, I'm starting to experiment a bit with html5 video. I wrote a small class to manage video's.

const videoLayer = document.getElementById( "videoLayer" );

class videoPlayer {
    constructor( id, source ){
        this.id = id;
        this.source = source;
        videoLayer.innerHTML +=  
            `<video id="${ this.id }">
                <source src="${ this.source }" type="video/mp4">
            </video>`;
        this.element = document.getElementById( this.id );
        this.element.onended = () => {
            this.stop();
        }
        this.hide();
    }

    show(){
        this.element.style.display = "inline";
    }

    hide(){
        this.element.style.display = "none";
    }

    goToStart(){
        this.element.currentTime = 0;
    }

    play(){
        this.show();
        this.element.play();
    }

    pause(){
        this.element.pause();
    }

    stop(){
        this.pause();
        this.hide();
        this.goToStart();
    }

    toggle(){
        this.show();
        this.element.paused ? this.element.play() : this.element.pause();
    }
}

With only one instance, it all works just fine. But with multiple instances, only the last instance is working. If I use .play() on the first instance, only the audio starts playing. If I look at "inspect element" I can see that the display property keep showing "none". The weird thing is, if I add the following lines to the console, everything works fine.

const test = document.getElementById( theRightId );
test.style.display = "inline";
test.play();

If I add the line beneath to the show function, it returns the right element in the console. However, there it states that the display value is "inline".

console.log( this.element );

So I suspect that something is messing with the display value after execution.

And lastly, if I change the order of the instances, they all work as long as they are the last created instance.

Any ideas?

  • It turns out that is all responds the same way in edge. I'm really sorry if I'm staring blind on some stupid and obvious mistake – Laurens Mathues Aug 14 '21 at 22:40
  • When you add the second videoPlayer, you read the HTML inside `videoLayer`, add new video tag to it, then **overwrite the previous DOM** with a new DOM generated from your new HTML. At that point the DOM no longer contains the element which `this.element` from the first videoPlayer points to (instead it contains a new element with the same id). – Quentin Aug 14 '21 at 22:53

0 Answers0