I have a page with a (image) button and a video element. Whenever I click the button, I want to load and start playing a random video. However, even though src gets set correctly to a random file, the video player does not change. What could be the problem? The code is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test</title>
</head>
<body>
<div id="all">
<div id="video-container">
<video width="500" controls>
<source id="vid" src="videos/1.mp4" type="video/mp4">
Your browser does not support HTML5 video.
</video>
</div>
<div id="buton">
<img src="img/buton.png" onclick="swapVid()">
</div>
</div>
<script type="text/javascript">
function swapVid() {
console.log("videos/"+Math.round(Math.random() * 3).toString() + ".mp4")
document.getElementById("vid").setAttribute("src", "videos/"+Math.round(Math.random() * 3).toString() + ".mp4")
console.log(document.getElementById("vid").getAttribute("src"))
}
</script>
</body>
</html>
You can also do it without replacing the existing video element as listed below. For this the id="vid" should be an attribute of <video> element. I suppose this is what you tried to do:
<div id="all">
<div id="video-container">
<video width="500" controls id="vid" src="videos/1.mp4">
Your browser does not support HTML5 video.
</video>
</div>
<div id="buton">
<img src="img/buton.png" onclick="swapVid()">
</div>
</div>
<script type="text/javascript">
function swapVid() {
var nextVideo = "videos/" + Math.round(Math.random() * 3).toString() + ".mp4";
document.getElementById("vid").setAttribute("src", nextVideo);
console.log(document.getElementById("vid").getAttribute("src"));
}
</script>
Perhaps you could take a different approach to this problem, by replacing the existing video with an entirely new video element:
function swapVid() {
var video = document.getElementById('vid');
if(video) { video.remove(); }
video = document.createElement('video');
video.setAttribute('id', 'vid');
video.width = 500;
video.src = "videos/"+ parseInt(Math.random() * 3) + ".mp4";
}
Taking this approach ensures that no "stale" state (ie play state, cursor position, etc) from prior video playback carries over to next randomly selected video.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With