My editors would like our embedded YouTube videos to start playing in a modal overlay when someone clicks on the video.
I have managed to get the videos to load in a modal overlay and to start playing. But I can only get them to play when I append &mute=1
to the YouTube embed URL.
Is there a way to get them to play with audio? After all, we only load the video into the modal after a user has signaled intent to view it by clicking on it.
My HTML:
<section>
<div class="container">
<div class="row">
<div class="sizer">
<div class="overlay" data-toggle="modal" data-target="#ModalBox">
<iframe
src="https://www.youtube.com/embed/iRYDYrj3Bfw"
frameborder="0"
allow="autoplay; encrypted-media"
allowfullscreen></iframe>
</div>
</div>
</div>
</div>
</section>
<!-- Modal -->
<div class="modal fade" id="ModalBox" 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" allowfullscreen>></iframe>
</div>
</div>
</div>
</div>
</div>
My CSS:
.width {
width: 560px;
height: 315px;
}
.sizer {
width: 560px;
height: 315px;
}
.overlay {
position: relative !important;
cursor: pointer !important;
width: inherit !important;
}
.overlay:before {
content: '';
position: absolute;
height: 100%;
width: 100%;
transition: all 200ms ease-in;
opacity: 0;
}
.overlay:hover:before {
background: #999999;
opacity: 0.3;
}
body {
margin: 2rem;
}
.modal-dialog {
max-width: 90%;
margin: 30px auto;
}
.modal-body {
position: relative;
padding: 0px;
}
.close {
position: absolute;
right: -30px;
top: 0;
z-index: 999;
font-size: 2rem;
font-weight: normal;
color: #fff;
opacity: 1;
}
.modal-backdrop {
opacity: 0.8 !important;
background: #000;
}
My JavaScript:
$(document).ready(function() {
// get the video src from the youtube iframe
var $videoSrc = $("iframe").attr("src").split('?')[0];
// when the modal is opened autoplay it
$('#ModalBox').on('shown.bs.modal', function (e) {
// set the video src to autoplay and not to show related videos.
var $videoSrcAuto = $videoSrc + "?rel=0&autoplay=1&mute=1";
$("#video").attr('src',$videoSrcAuto);
})
// stop playing the youtube video when modal is closed
$('#ModalBox').on('hide.bs.modal', function (e) {
$("#video").attr('src',$videoSrc);
})
// document ready
});
A working example: https://codepen.io/CodeChaos/pen/NExWWo
Update 1:
Upon further research this issue appears to be happening only in Chrome. In Edge and Firefox I am able to get the videos to autoplay even without muting.