Stop the iframe video when the modal is closed

I'm currently developing a website that incorporates the code showcased in this tutorial to launch a modal window featuring an iframe for playing YouTube or Vimeo videos.

The issue arises when, as mentioned in the comments on the tutorial page, there's no provision in the code to pause the video when the modal is closed either by using the close button or clicking outside the video area. Since I have limited experience with JavaScript, I've tried implementing all the suggestions from the comments without success. It seems like the recommendations assume a higher level of JS knowledge than what I possess. Hence, I would greatly appreciate it if someone could provide an explanation in simpler terms - almost like explaining to a five-year-old child.

Below is the JavaScript code snippet:

jQuery(document).ready(function() {

$('.launch-modal').on('click', function(e){
    e.preventDefault();
    $( '#' + $(this).data('modal-id') ).modal();
});

});

And here's the HTML markup for the modal:

        <!-- MODAL-->
        <div class="modal fade" id="modal-video" tabindex="-1" role="dialog" aria-labelledby="modal-video-label">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="modal-video">
                            <div class="embed-responsive embed-responsive-16by9">
                                <iframe src="https://www.youtube.com/embed/cp-Tt3aOYVY" frameborder="0" allowfullscreen></iframe>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-lg-8 col-lg-offset-2 text-center">
                                <br><br>
                                <h4 class="section-heading">Lorem Ispum</h4>
                                <hr class="primary">
                                <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

Furthermore, here's the associated CSS code:

.modal-backdrop.in {
opacity: 100;
background: white;
}

.modal-content {
background: none;
border: 0;
-moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;
-moz-box-shadow: none; -webkit-box-shadow: none; box-shadow: none;
color: black;
}

.modal-body {
padding: 0 25px 25px 25px;
}

.modal-header {
padding: 25px 25px 15px 25px;
text-align: right;
}

.modal-header, .modal-footer {
border: 0;
}

.modal-header .close {
float: none;
margin: 0;
font-size: 36px;
color: black;
font-weight: 300;
text-shadow: none;
opacity: 1;
}

.modal-dialog {
width: 80%;
margin: 0px auto;
color: black;
}

Your assistance on this matter would be immensely appreciated!

Answer №1

After consulting with my tech-savvy cousin who has a knack for coding, we were able to fix all the issues by updating the JS code to:

jQuery(document).ready(function() {

    $('.launch-modal').on('click', function(e){
        e.preventDefault();
        var $modalElement = $('#' + $(this).data('modal-id'));
        $modalElement.modal();
        var $iframe = $modalElement.find('iframe')[0];
        $modalElement.on('hide.bs.modal', function (e) {
            $iframe.src = $iframe.src; 
        });
    });
});

Answer №2

If you want to improve your code functionality, consider detaching the functions linked to your button and implementing a new jQuery event to signal when the close button is clicked:

$("#closebutton").click(function(){
   $("iframe").remove();   //For added precaution
   $(".modal").remove();
});

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

The jquery live click event is not functioning properly on iPad devices

I am experiencing an issue with a webpage that has the following code to bind click events <script type="text/javascript"> $(".groupLbl").live("click", function(e) { var $target = $(e.currentTarget); ..... $.getJSON("/somelink.js ...

Invoke a functional component when a button is clicked in a React application

I have a functional component that includes a button. My goal is to trigger another functional component when this button is clicked. Upon clicking the Submit button, the Preview button appears. When the user clicks on the preview button, it should call t ...

I'm noticing that my Tailwind styles don't take effect until I redefine them. What could be causing

My Tailwind classes are giving me trouble. I faced an issue when I created a new component in the directory and placed my Button component there. Whenever I restart the project in terminal, the styles do not apply to my button unless I manually define th ...

Guide on how to compile template strings during the build process with Babel, without using Webpack

I'm currently utilizing Babel for transpiling some ES6 code, excluding Webpack. Within the code, there is a template literal that I wish to evaluate during the build process. The import in the code where I want to inject the version looks like this: ...

Express JS res.send() with an array response data is posing a concern during the Checkmarx scan

When using the axios library in my express middleware to retrieve responses from APIs, I encountered a security concern raised by Checkmarx scan report. router.post(someurl,req,res) { axios .get(someurl) .then((response=>{ **res.send(response.data);**/ ...

Using the Table-multiple-sort feature in boostrap-table is not functioning properly when there are multiple tables present on a single page

I have implemented bootstrap-table along with the extension table-multiple-sort. The issue I am facing is when I include two tables on a single page (with the second table within a modal window), the multisort feature does not seem to work on the second ta ...

Is there a method to measure the time it takes to download a script apart from its actual execution time

I am looking to track timing variables for my primary JavaScript load. One approach could be: <script> performance.mark('script-start') </script> <script src="something.js"></script> Later in something.js, inc ...

Using jQuery to smoothly animate scrolling to the top of a

How can I create a "scroll to top" button at the bottom of my page that smoothly scrolls to the top? Despite using an "animate({scrollTop})" script, the scroll animation is not working and it jumps directly to the top. This is the script I am using: $(&a ...

Arranging data using jqGrid's Inline Editing Feature

Can the data on jqGrid be sorted directly on the client side while using inline editing? It appears that the data is not being sorted when the row is editable, even if the row header is clicked. ...

Information derived from a provided URL

I am currently developing a Spotify stats app, and I am facing an issue with creating a context to store the token provided by the app in the URL when a user logs in. TokenContext.js: import React, { useEffect, useState } from "react"; // token ...

Evaluating CSS Specificity

Is there a recommended approach for automatically testing css selectors? I am in the process of developing a SCSS framework and I want to integrate automated tests. Specifically, I aim to verify that the css selectors are functioning correctly. For examp ...

Hamburger Icon in Bootstrap Navbar-Brand is not aligned as expected

I'm currently working on a website project using Bootstrap and have encountered an issue with the navbar component. When the screen shrinks to the breakpoint I've defined (lg), the alignment of the hamburger icon gets disrupted, as shown below. ...

React unit tests experiencing issues with MSW integration

After creating a basic React application, I decided to configure MSW based on the instructions provided in order to set it up for unit tests in both node environment and browser. The main component of the app utilizes a custom hook called useFormSubmission ...

What is the Best Way to Enable Tooltips to Function from External Elements?

I am currently designing a map that features points with tooltips. When hovered over, the tooltips function correctly. I am interested in exploring the possibility of making the tooltips interact with an external navigation bar. My goal is to have specifi ...

Balanced Height Panels - Utilizing Flexbox and flex-wrap: wrap

i'm having trouble with a layout design, specifically with getting the columns to be equal height, especially when the text wraps around. Can anyone provide some guidance? https://i.stack.imgur.com/bbDKj.png Within my HTML template, there are multipl ...

Manipulating rows [using an input field] within a table

As someone new to JavaScript, I tried my hand at coding the following piece after tweaking a tutorial I stumbled upon. The aim was to have rows with input fields added and removed within a table, but unfortunately, nothing happens when running the code. ...

Modify styling of complete list upon clicking in React

For my latest project, I developed a basic todo application using React. One of the key features is that when a user clicks on a checkbox, the corresponding todo item's CSS changes to show a strike-through effect. Additionally, a button appears on hov ...

Setting a default action for an Ext.Ajax.request error situation

In my application, I frequently make ajax requests using the Ext.Ajax.request method. Often, I find myself skipping error handling for failed requests due to time constraints or lack of interest in implementing fancy error handling. As a result, my code us ...

Send a string from an AJAX request to a PHP script

My goal is to retrieve a value from an input field, send it through ajax to PHP, and then store the data in a MySQL table. The database structure is already in place, so I just need to insert the values. Here is my JavaScript file: var address = $("input ...

Guide on passing a JSON body as a string in a PUT API request using Fetch in a React.js application

How can I pass a JSON body as a string in a FETCH PUT API in React JS? I am attempting to add 20 to the Balance like this: Balance: details[0].Balance.toString() + 20, but it is not working as expected. I want the entire result to be a string. Any assista ...