Trying to get a trailer looped until the user clicks somewhere on the screen after which the lecture video is supposed to play once and then revert to the trailer. Managed to find a similar question here on StackOverflow, unfortunately, I'm unable to get it to fully work. The trailer loops and when I click on the button the lecture video plays but does not start the trailer video and instead just loops the lecture video.
What am I doing wrong here?
<video id="mp4Source" autoplay loop controls width="100%" src="/assets/trailer.mp4" >
</video>
<button type="button" name="button" onclick="playLectureVid()"> Play Lecture Vid</button>
function playLectureVid(){
var video = document.getElementById("mp4Source");
video.src = '/assets/lecture.mp4';
video.load();
video.play();
video.addEventListener("ended", function(e) {
e.currentTarget.removeEventListener(e.type, handler);
video.src = '/assets/trailer.mp4';
video.load();
video.play();
});
}
Just toggle between two videos.
var trailer = document.getElementById("trailer");
var lecture = document.getElementById("lecture");
function playLectureVid() {
lecture.style.display = 'block';
trailer.style.display = 'none';
trailer.pause();
lecture.play();
}
lecture.addEventListener("ended", function(e) {
trailer.style.display = 'block';
lecture.style.display = 'none';
lecture.pause();
trailer.play();
});
video {
width: 400px;
}
#lecture {
display: none;
}
<center>
<button type="button" name="button" onclick="playLectureVid()"> Play Lecture Vid</button>
<br>
<video id="trailer" autoplay muted loop controls width="100%" src="https://jsoncompare.org/LearningContainer/SampleFiles/Video/MP4/Sample-MP4-Video-File-for-Testing.mp4"></video>
<video id="lecture" controls width="100%" src="https://samplelib.com/lib/preview/mp4/sample-5s.mp4"></video>
</center>
Instead of using video.addEventListener("ended",, you can use video.onend = () => {code here}. Then, because this is called every time the video ends, insert these lines to the top of your function:
if (trailerLoaded) return
trailerLoaded = true
and add this at the top of playLectureVid:
var trailerLoaded = false
This will make it so that the video will not be reloaded every time it ends.