PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, April 16, 2022

[FIXED] How do I stop Audio/Video playback in a Modal with jQuery?

 April 16, 2022     html, iframe, jquery, modal-dialog     No comments   

Issue

I've been trying to figure out how to stop the audio from playing after closing a modal, and nothing seems to work.

My attempt

<script>
var docReadyCodeForModal = setInterval(function() {
    if(jQuery) {
        clearInterval(docReadyCodeForModal);
       $("#myModal").modal('show');
       $("#stopClose").click(function(){
           $("#myModal").modal('pause');
    });
    }
}, 100);
</script>

<div aria-hidden="true" class="fade modal" id="myModal" style="display:none">
<div class="modal-lg modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" style="text-align:center">WELCOME TO THE THUNDERDOME!!!</h5>
<button id="stopClose" class="close" data-dismiss="modal" type="button">&times;</button></div>

<div class="modal-body">
<div class="embed-responsive embed-responsive-16by9"><iframe class="embed-responsive-item video-not-resize" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" src="https://www.youtube.com/embed/yGwjyodRst4?autoplay=1" title="YouTube video player"></iframe></div>
</div>
</div>
</div>
</div>

Note: video link removed for privacy reasons.

I appreciate any insight into this issue


Solution

Script to stop the video from playing when closing modal

Add an id to your iframe and replace #iframe-id with that id.

$(document).ready(function(){

        var url = $("#iframe-id").attr('src');
            
        $("#myModal").on('hide.bs.modal', function(){
            $("#iframe-id").attr('src', '');
        });
            
        $("#myModal").on('show.bs.modal', function(){
            $("#iframe-id").attr('src', url);
        });

});

You are using Bootstrap. This script listens to the Bootstrap events when hiding and showing the modal.

It removes the url from the iframe src attribute when closing modal and adds the url when the modal its opened.



Answered By - Gass
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing