I want my code to play a video but when I close the modal the music in the video still plays on the background.
<div class="modal fade" id="videoModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="" id="video" allowscriptaccess="always" allow="autoplay"></iframe>
</div>
</div>
</div>
</div>
</div>
I tried using jquery to fix it but nothing happens.
$(document).ready(function () {
var $videoSrc;
$('.btn-play').click(function () {
$videoSrc = $(this).data("src");
});
console.log($videoSrc);
$('#videoModal').on('shown.bs.modal', function (e) {
$("#video").attr('src', $videoSrc + "?autoplay=1&modestbranding=1&showinfo=0");
})
$('#videoModal').on('hide.bs.modal', function (e) {
$("#video").attr('src', $videoSrc);
})
});
To do what you require you can either stop or pause the video playing when the hide.bs.modal event fires.
You can do this by sending a postMessage to the iframe containing the embedded Youtube player. Note that the enablejsapi=1 parameter has to be included in the embed URL for this to work.
Here's a simplified example:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div><a href="#" class="play-video">Play Video</a></div>
<div><a href="#" class="stop-video">Stop Video</a></div>
<div><a href="#" class="pause-video">Pause Video</a></div>
<iframe class="embed-responsive-item" id="video" width="560" height="315" src="https://www.youtube.com/embed/LDU_Txk06tM?enablejsapi=1&version=3&playerapiid=ytplayer" allowscriptaccess="always" allow="autoplay"></iframe>
let videoIframeContent = $('#video')[0].contentWindow;
// stop
videoIframeContent.postMessage(JSON.stringify({"event": "command", "func": "stopVideo" }), '*');
// pause
videoIframeContent.postMessage(JSON.stringify({"event": "command", "func": "pauseVideo" }), '*');
Here's a working demo in a jsFiddle and the snippet editor is sandboxed and won't allow video.
That's because the video wasn't stopped.
In the listener that listens to the hide.bs.modal event:
const video = $('#video').get(0);
video.pause();
video.currentTime = 0;