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

CSS: elements that are only visible when positioned above specific elements

Can we create an element that is only visible above specific other elements? For instance, in the following code snippet, I want the .reflection element to be visible only above the .reflective elements (located at the top and bottom) and not visible on t ...

Select the date that is three months from now using the datetimepicker feature of Bootstrap

I have two datetimepicker fields for selecting a start date and end date. I am utilizing the eonasdan datetimepicker plugin for Bootstrap. I am trying to set the range from the current date up to 3 months ahead. However, when I use maxdate:'+90d&apo ...

React-file-viewer shrinks any document to a compact size

I have been searching extensively for information on how to adjust file sizing in react-file-viewer without any success. My objective is to utilize the react-file-viewer to allow users to click on a filename hyperlink and open the file (be it an image, do ...

Using Django Sessions for User Authentication in React Applications

Not a coding query, but rather a general one: When using default authentication in Django (session authentication), what does the frontend (in my case it's React) require? For instance, upon logging in on the browser via the front end login button, th ...

Using npm to trigger the package.json file will activate both the harp and browser-sync applications

I am looking for a way to simultaneously start a harp.js server and run a browser-sync process. This setup works perfectly on Linux with the following package.json configuration: { "scripts": { "dev": "bash ./serve.sh" } } Here is the content of ...

Is there a more efficient method to execute this AJAX request?

$('#request_song').autocomplete({ serviceUrl: '<%= ajax_path("trackName") %>', minChars:1, width: 300, delimiter: /(,|;)\s*/, deferRequestBy: 0, //miliseconds params: { artists: 'Yes' }, onSelect: functi ...

Searching the Google Place API to generate a response for dialogflow

I am currently facing an issue while trying to utilize the Google Place API for retrieving details to display a map (by fetching coordinates) and location information (address) as a response from my chatbot. I have created this code snippet, but encounteri ...

Exporting JSON data to an Excel file using an array of objects with embedded arrays

I am currently developing a fitness application that allows users to create workout routines and download them as an excel file. The data is structured as an array of objects, with each object representing a workout date and containing details of the exerc ...

What is the best way to utilize AJAX to send a value from a foreach loop in Laravel?

I'm encountering an issue where all forms are sending the value as if it's from the first form, however, my intention is for each form to send the data inside it when I press the send button. Blade @foreach($car_lists as $car_list) <li class= ...

Include the script tags retrieved from an array

I'm exploring the idea of dynamically adding JavaScript to the DOM using an array and a loop. The goal is to load each script sequentially, starting with scripts[0], then scripts[1], and so on. var myScripts = [["external", "https://code.jquery.com/j ...

Generating numerous circular elements for each item in the dataset using D3

My dataset consists of various years and corresponding numerical values for each year as shown below: "data":[ ["1951","306","27","159","34","82","4"], ["1956","426","41","203","47","119","16"], ["1959","562","67"," ...

When executing class methods, Ember.js encounters errors stating "method does not exist."

I am facing a situation where I need to trigger a model reload when a user clicks a refresh button. In the past, I successfully implemented this with Ember-Model. However, since migrating to Ember-Data, I am encountering an error when attempting to execute ...

The type 'true | CallableFunction' does not have any callable constituents

The error message in full: This expression is not callable. No constituent of type 'true | CallableFunction' is callable Here is the portion of code causing the error: public static base( text, callB: boolean | CallableFunction = false ...

JavaScript is utilized to implement the k-means clustering algorithm, which demonstrates convergence yet lacks stability in its

Although I understand the concept of convergence, I am puzzled by the fact that the results vary each time the algorithm is refreshed, even when using the same dataset. Can someone point out where my methodology might be incorrect? I've been strugglin ...

PHP: Retrieving the ID of the clicked cell

I am trying to retrieve the ID of a cell when it is clicked on. Below is the code I am using to print my table: public function DrawBoard(){ echo '<table id="board">'; $i = 0; for($row= 0; $row < 8; $row++){ ...

Ways to incorporate CSS design into Django input pop-up when the input is invalid

Looking to enhance the error message styling for a Django Form CharField when an incorrect length is entered, using CSS (Bootstrap classes preferred). I have successfully styled the text input itself (check the attrs section in the code), but I am unsure ...

The pair of divs with distinct backgrounds

Looking to customize the navigation on my website by creating a separate background for the list links menu and making sure the left part of the navigation with the logo has its own distinct background that extends until the next div. I've experimente ...

The error "relative error: invalid property value" occurs when setting the width and height of a parent element

I'm having trouble getting my h2 text to appear above my images when hovered over. I keep receiving an error message in Chrome Developer Tools saying that "display: relative" is not a valid property value, but I can't figure out why. I've se ...

Optimizing performance: Making the most of mongoose updateMany middleware

PROBLEM SOLVED: SOLUTION PROVIDED BELOW I have a piece of code where I am updating elements one by one: //registerCustomers.js const CustomerRegistrationCode = require("../models/CustomerRegistrationCode"); const setRegCodesToUsed = async (regC ...

How to verify if a node contains plaintext with jsoup?

Is there a way to determine if a node in jsoup has plain text without including link text, instead of using the Element.hasText() method? Any suggestions would be greatly appreciated. Thank you ...