This code is playing video on floating windows using bootstrap. But i want to modify the video src using javascript so i can have dynamic video link. I use onClick() to change the src of the video but it didn’t work.
function changevideo() { document.getElementById("source").src = "videos/projects/havoc/guide/guide_GOL_101_019_010.mp4"; }
<!DOCTYPE html> <html lang="en"> <head> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"> </script> </head> <body> <button width="200" data-bs-toggle="modal" data-bs-target="#video" class="img" onClick="changevideo()">click me 1</button> <!-- Modal --> <div class="modal fade" id="video"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-body"> <video width="100%" autoplay loop> <source id="source" src=""> </video> </div> </div> </div> </div> </body> </html>
Advertisement
Answer
You just forgot to press play
.
const video = document.getElementById("video-element"); const clear = (node) => { while (node.firstChild) { node.removeChild(node.lastChild); } }; const changevideo = () => { const source = document.createElement('SOURCE'); clear(video); source.type = "video/mp4"; source.src = "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"; video.appendChild(source); video.play(); }
<!DOCTYPE html> <html lang="en"> <head> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"> </script> </head> <body> <button width="200" data-bs-toggle="modal" data-bs-target="#video" class="img" onClick="changevideo()">click me 1</button> <!-- Modal --> <div class="modal fade" id="video"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-body"> <video id="video-element" width="100%" loop> </video> </div> </div> </div> </div> </body> </html>