Stop YouTube Video inside Modal from Playing on Modal Close
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I am using micromodal.js https://micromodal.now.sh/
I need to use their onClose: to stop or pause videos inside of modals when the modal is closed.
Here is an example of the onClose:
MicroModal.init({
onClose: modal => console.info(${modal.id} is hidden),
});

I have this working in jQuery but I am moving everything to vanilla and I can't figure this one out.
Here is my working jQuery version for reference but it DOES NOT use micromodals onClose:

$(document).ready(function() {
$(".close").click(function () {
$(".d3-youtube-iframe").each(function () {
$(this).attr('src', $(this).attr('src'));
//return false;
});
});
});

awarded to Sanjo
Tags
javascript

Crowdsource coding tasks.

2 Solutions

Winning solution

Here's a one-to-one translation of your jQuery code to vanilla JavaScript and using MicroModal.

MicroModal.init({
    onClose: modal => {
        document.querySelectorAll('.d3-youtube-iframe').forEach(iframe => {
            iframe.setAttribute('src', iframe.getAttribute('src'));
        });
    },
});

EDIT: Here is a variation that only considers .d3-youtube-iframe elements inside the modal that is closed.

MicroModal.init({
    onClose: modal => {
        modal.querySelectorAll('.d3-youtube-iframe').forEach(iframe => {
            iframe.setAttribute('src', iframe.getAttribute('src'));
        });
    },
});
Freakin awesome!
twd 30 days ago

HTML:

<div class="modal micromodal-slide" id="modal-1" aria-hidden="true">
    <div class="modal__overlay" tabindex="-1" data-micromodal-close>
    <div class="modal__container" role="dialog" aria-modal="true" aria-labelledby="modal-1-title">
        <header class="modal__header">
        <button class="modal__close" aria-label="Close modal" data-micromodal-close></button>
        </header>
        <main class="modal__content" id="modal-1-content">
        <!-- VIDEO -->
        <iframe width="560" height="315" src="https://www.youtube.com/embed/Bs68k6xfR3E?version=3&enablejsapi=1" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
        <!-- VIDEO -->
        </main>
    </div>
    </div>
</div>
<button data-custom-open="modal-1">Show Modal</button>

JAVASCRIPT:

MicroModal.init({
    openTrigger: 'data-custom-open',
    onClose: modal => {
    const iframe = document.querySelector('iframe');
iframe.contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*');

    }
});
View Timeline