I have added the following code to my html page to stop a modal video from playing when closing it:
<head>
<script type="text/javascript">
$(document).ready(function(){
$('.modal').each(function(){
var src = $(this).find('video').attr('src');
$(this).on('click', function(){
$(this).find('video').attr('src', '');
$(this).find('video').attr('src', src);
});
});
});
</script>
</head>
<body>
<div class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">My title</h4>
</div>
<div class="modal-body">
<div> <video controls width="100%"> <source src="videos/myvideo.mp4" type="video/mp4"></video> </div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</body>
It works fine with Firefox but not with Chrome and Safari. On Firefox, the src link is removed when closing the modal (good). On Chrome, when I click the playing bar of the video inside the modal, Chrome starts the video but if I click the video itself (which should just pause/play it) it removes the src link, so the video becomes black. Safari removes the src link as soon as clicking play (so the video never starts). My priority is to make this work on Firefox and Safari.
Does anyone have any idea how I could solve this?
(Note: I have tried other codes to make the video stop when modal is closed, to see if it could work better with Safari and Chrome (for example, here Twitter Bootstrap Modal stop Youtube video) but I could not manage to make the video stop at all. So the one I use in this example is the only one that correctly stops my video from playing when closed – at least in Firefox.)