The video continues playing even after closing the modal box

I am facing an issue with my code where a video continues to play in the background even after I close the modal. Here is the code snippet:

<div class="modal fade" id="videoModal" 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">&times;</span>
                </button>       
                <!-- 16:9 aspect ratio -->
                <div class="embed-responsive embed-responsive-16by9">
                    <iframe class="embed-responsive-item" src="" id="video"  allowscriptaccess="always" allow="autoplay"></iframe>
                </div>
            </div>
        </div>
    </div>
</div>

Despite trying to resolve this using jQuery, the issue persists.

 $(document).ready(function () {
    var $videoSrc;
    $('.btn-play').click(function () {
        $videoSrc = $(this).data("src");
    });
    console.log($videoSrc);

    $('#videoModal').on('shown.bs.modal', function (e) {
        $("#video").attr('src', $videoSrc + "?autoplay=1&amp;modestbranding=1&amp;showinfo=0");
    })

    $('#videoModal').on('hide.bs.modal', function (e) {
        $("#video").attr('src', $videoSrc);
    })
});

Answer №1

If you need to achieve a specific task, you have the option to halt or temporarily pause the video playback when the hide.bs.modal event is triggered.

This can be accomplished by utilizing the postMessage method to communicate with the iframe that hosts the embedded Youtube player. It's important to remember that the embed URL must include the enablejsapi=1 parameter for this functionality to take effect.

Below is a simplified example:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div><a href="#" class="play-video">Play Video</a></div>
<div><a href="#" class="stop-video">Stop Video</a></div>
<div><a href="#" class="pause-video">Pause Video</a></div>

<iframe class="embed-responsive-item" id="video" width="560" height="315" src="https://www.youtube.com/embed/LDU_Txk06tM?enablejsapi=1&version=3&playerapiid=ytplayer" allowscriptaccess="always" allow="autoplay"></iframe>
let videoIframeContent = $('#video')[0].contentWindow;

// stop 
videoIframeContent.postMessage(JSON.stringify({"event": "command", "func": "stopVideo" }), '*');

// pause
videoIframeContent.postMessage(JSON.stringify({"event": "command", "func": "pauseVideo" }), '*');

For a live demonstration, you can visit this jsFiddle. Please note that the snippet editor does not support video content due to sandboxing restrictions.

Answer №2

It appears that the video continued playing.

Within the event listener for the hide.bs.modal event:

const videoElement = $('#video').get(0);
videoElement.pause();
videoElement.currentTime = 0;

Answer №3

In my opinion, it would be beneficial for you to utilize the video tag rather than an iframe to have more control over the video playback. You can find more information on how to implement this by following this link

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why does this CSS ticker only display the first four posts?

Hello, I'm interested in adding a News Ticker to my Rails application. I came across this CSS ticker: I'm facing an issue where it only displays the first four posts. I believe the problem might not be with my data retrieval using the .each loop ...

Can other JavaScript event listeners be synchronized with an asynchronous event?

My goal is to manipulate a web page using Tampermonkey where there is a button with certain event listeners followed by a redirect. Is it possible for me to insert my own click event handler into the button, which triggers an AJAX request and waits for it ...

Acquiring JSON data within a JavaScript function using PHP

Requesting assistance on reading a JSON value using the code below, to retrieve data based on the $movieID. <script> function bookBTN(x) { <?php $url = 'http://movie.com/movieOne?seatNum=' . x; $jsonURL = file_get_ ...

Displaying a specific division solely on mobile devices with jQuery

I need to implement a feature where clicking on a phone number div triggers a call. However, I only want this div to be displayed on mobile devices. To achieve this, I initially set the div to "display:none" and tried using jQuery to show it on mobile devi ...

Guide to spinning a CannonJS RigidBody

Has anyone found a way to rotate a CANNON.RigidBody object in CannonJS (the physics library)? I'm attempting to align the object's rotation with that of the camera, so they both face the same direction. I understand that I need to adjust the quat ...

Scrolling infinitely in every direction - both upwards and downwards

I'm currently working on a page that I want to have an endless scrolling effect both up and down. Right now, I am using jQuery to move content from the top of the page to the bottom. This gives a smooth loop when scrolling down, but I also want it to ...

Exploring the power of Blowfish encryption with Java and JavaScript

I am facing an issue where I need to encrypt data using Blowfish on a java-based server and send it to a client. Despite successfully encrypting the data, I am unable to decrypt it on the client side. Below is my Java code snippet: byte[] kd = key.getByt ...

The issue with React Testing using Jest: The domain option is necessary

I've recently developed a React app that implements Auth0 for Authentication. Right now, I'm working on setting up a test suite using Jest to test a specific function within a component. The function I want to test is createProject() in a React ...

Is it necessary to dispose of node.js domains? When is the appropriate time to do so?

In my Express application, I utilize domains for each incoming request. To ensure that all subsequent middlewares are executed within a domain, I've implemented a middleware. app.use(function(req, res, next) { var d = domain.create(); d.req ...

The initial transition in offcanvas on bootstrap 5 is not appearing when a placement is dynamically added

I am currently working on triggering an Offcanvas with JS and making the placement configurable. The issue arises when attempting to dynamically set the offcanvas-end class to the offcanvas element, as it does not transition smoothly the first time it is t ...

Showing the Length of Several Videos Simultaneously on a Webpage

I am attempting to showcase the "duration" for each video on the page using JavaScript. This is my current code: var vid = document.querySelector(".mhdividdur"); vid.onloadedmetadata = function() { var x = document.querySelector(".mhdividdur").duratio ...

Pause and wait for the completion of the Ajax call within the function before assigning the object to an external variable

In my quest to leverage JavaScript asynchronously to its full potential, I am looking for a way to efficiently handle received data from API calls. My goal is to dynamically assign the data to multiple variables such as DataModel01, DataModel02, DataModel0 ...

React application not functioning on localhost:3000 despite successful compilation with no errors, only displaying the title on localhost but failing to show any content

I recently started developing a new website with React. Everything was running smoothly on localhost until I made some changes, and now the homepage content is not displaying when I visit localhost:3000. I suspect there may be an issue with my routing or s ...

Setting line chart data for Chart.js

Can you help me troubleshoot an issue I'm facing with creating a dataset for a line chart in Chart.js? Despite having an array of objects, the dataset isn't rendering correctly and I end up with two line charts instead of one. What could be causi ...

The footers on each page are not consistent

I have noticed that two pages utilizing the same CSS are displaying differently. Check them out here: 128.48.204.195:3000 128.48.204.195:3000/formats If you look closely, you'll see that below the footer, the /formats page appears to have no extra s ...

Determine the absent information by comparing two JSON objects with JavaScript

Two JSON objects, counties and ctyIndem, are at hand. The counties object contains all the counties in a specific US State, while ctyIndem holds information about indemnities paid in that State by county, excluding those with no payments made. My task is t ...

React Component: Issue with conditional "if else" statement not refreshing in return statement

Starting out in React and the front-end field with minimal experience. Currently attempting to dynamically change the color of the "fill" property in a polygon element using React. If the percentage is greater than 50, I want the color to be green; otherw ...

Find out if all attributes of the object are identical

I am trying to create the boolean variable hasMultipleCoverageLines in order to determine whether there are multiple unique values for coverageLineName within the coverageLines items. Is there a more efficient way to write this logic without explicitly c ...

Add data to a nested array with Vuex

Currently, I am facing a challenge with adding an object to a nested array in Vue using store / vuex. While I have successfully updated the main comments array with a mutation, I am struggling to identify the specific main comment to which the new reply ob ...

Let's discuss how to include the scrollTop option

I am new to coding and I need help adding a scrollTop margin of +100px to my code. The page already has some top margin but I can't seem to locate it. I'm also having trouble finding where the margin-top is being set in the JavaScript file. /*** ...