Home > Mobile >  jQuery prevent autoplay after user closes video
jQuery prevent autoplay after user closes video

Time:10-21

I'm writing a script that will pop-up a video and autoplay it following this example. Everything is working fine, however when the user closes the video, it continues playing in the background. How can I tell the browser to turn off autoplay after the user closes the video?

$(document).ready(function() {
  $('#headerVideoLink').magnificPopup({
    type: 'inline'
  });
});
#headerPopup {
  width: 75%;
  margin: 0 auto;
  position: relative;
  top: 80px;
}

#headerPopup iframe {
  width: 100%;
  margin: 0 auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="headerPopup" class="mfp-hide">
  <iframe width="854" height="480" src="https://www.youtube.com/embed/qN3OueBm9F4?autoplay=1" frameborder="0" allow="autoplay" allowfullscreen></iframe>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

From my point of view, there is no straight forward answer to your problem. This is a common thing people encounter when trying to show videos on websites.

The best approach to do this, is by using the Bootstrap CSS framework, because it has modals (pop ups) where you can add a video and whenever you close or open them it exposes events that can trigger functionalities.

In this case, you need jQuery to do something when opening and closing the modal. To avoid the video from playing on the background when the user closes the modal, one way would be to remove the content of the src attribute of the iframe, that will prevent the iframe to continue playing the video. And then when the user opens the modal add the link back. If you don't do this, what will happen is that the user may click on the video one time, it will work fine, but then after jQuery removed the link of the video, it wont work.

jQuery script I use for this purpose:

$(document).ready(function(){
            
     // Save the url of the video in a variable
     var url = $("#MyVideo").attr('src');
            
     // When the modal is closed remove the url of the iframe
     $("#myModal").on('hide.bs.modal', function(){
        $("#MyVideo").attr('src', '');
     });
            
     // When the modal is opened, add the url to the iframe
     $("#myModal").on('show.bs.modal', function(){
        $("#MyVideo").attr('src', url);
     });
});

You can read more about how Bootstrap modals work here. The details and explanations of the events are on the bottom of the page.

  • Related