Stop youtube video when modal closes

Hello. I need to put 3 or more modals and that when the client closes the modal, the YouTube video pauses and does not find the solution. Help…

example

Use Solution found below…

1 Like

You only need one modal
set the attributes on the modal trigger element
You can set start and end time in seconds for a short clip of the video
0 for the whole video

The modal trigger element in this case a button

<button class="btn btn-outline-dark btn-lg d-flex mx-auto mt-4" 
	type="button" 
	data-video="I40wkgqhb3A" 
	data-start="0" 
	data-end="0" 
	data-bs-toggle="modal" 
	data-bs-target="#showtime" 
	data-controls="0">What's new in Bootstrap Studio 6.3
</button>

The modal

<div class="modal fade" role="dialog" tabindex="-1" id="showtime">
	<div class="modal-dialog modal-xl modal-dialog-centered" role="document">
		<div class="modal-content">
			<div class="modal-body">
				<button class="btn btn-close" 
					id="close" 
					style="display: none;" 
					data-bs-dismiss="modal" 
					aria-label="Close">
				</button>
				<div class="ratio ratio-16x9">
					<iframe id="video" 
						title="tube" 
						allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; fullscreen">
					</iframe>
				</div>
			</div>
		</div>
	</div>
</div>

javascript

  const videoModal = document.getElementById('showtime');
  if (videoModal) {
    const modal = new bootstrap.Modal(document.getElementById('showtime')),
      video = document.getElementById('video');
    videoModal.addEventListener('show.bs.modal', (event) => {
      let v = event.relatedTarget,
        videoID = v.getAttribute('data-video'),
        start = v.getAttribute('data-start'),
        end = v.getAttribute('data-end'),
        controls = v.getAttribute('data-controls'),
        origin = window.location.hostname;
      video.src = `https://www.youtube.com/embed/${videoID}?autoplay=1&start=${start}&end=${end}&controls=${controls}&loop=1&rel=0&origin=${origin}`;
      let length = (end - start) * 1000;
      if (end > 0) setTimeout(() => modal.hide(), length);
    });
    videoModal.addEventListener('hide.bs.modal', () => (video.src = ''));
  }
3 Likes

@kuligaposten your js is always so beautiful to read. I’m not even going to bother with what I was about to post :rofl:

2 Likes

Thank you, I’ve tried it. and it works 100% thank you…