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

How can I retrieve the value from an input form using jQuery if it returns null?

Despite trying various methods, I have been unsuccessful in retrieving form values using jQuery and sending them in an AJAX GET request. The value keeps showing as null even after spending more than 18 hours on it. Any help would be greatly appreciated. $ ...

Tips for waiting for an event from a specific element in Playwright

Is there a way to await an event on a specific element using Playwright? Similar to page.waitForEvent, but focusing only on a particular element rather than the entire page. More information can be found in the documentation. ...

Is there a way to call and update an Angular controller's $scope from external sources?

function in controller: $scope.updateData = function () { Words.fetch('update', $scope.randNum) .error(function (data) { console.log('update error: ' + data.message); }) ...

Tips for ensuring that a nested object in an array contains only a single object

My array is structured like this: [ { object1:{ childObj1:[grandChild1,grandChild2], childObj1, childObj1} }, { object2:{ childObj1:[grandChild1,grandChild2], childObj1, childObj1} }, { object3:{ childObj1:[grandChild1,grandChild2 ...

Fixing the problem of digest overflow in AngularJS

I've been working on a code to display a random number in my view, but I keep encountering the following error message: Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! It seems to be related to a digest outflow issue, and I&apo ...

Having trouble with the $.get function in AJAX with Rails 4? It seems

After working with Rails for a few years, I decided to dip my toes into the world of AJAX. With a Rails 4 app in hand, I'm currently testing out some functions. My end goal is to reload a partial on the edit page located at app/views/stories/edit.html ...

Display an icon within an HTML element when the content inside it exceeds its boundaries

Looking to display a copy to clipboard icon when the content inside a div overflows I am using ngFor to iterate through four divs, and if any of those divs is overflowing, I want to show an icon specific to that respective div. <div *ngFor div of Four ...

The fetch method in Express.js resulted in an error 404 because the requested URL could not be found

Having trouble locating the URL when trying to fetch data for a POST request. I want to mention that my code is written in node.js and express.js. The error message being generated: const form = document.querySelector('form'); form.addEventList ...

Loop through a collection of items based on the values in a separate array using jQuery

I have a list of objects below The newlist and SelectID array are both dynamic. I am populating through a function, now I need to iterate and create the new list. var newList = [ { id : 1,name="tea",plant:"darjeeling"}, { id : 2,name="cof ...

Using JQuery to append elements and then locate them with the find method does not produce the expected

Hey there, I'm having trouble inserting one DOM element into another. It's something I've done many times before successfully, but for some reason it's not working this time and I can't figure out why. Currently, I am using an Aja ...

Angular's Enhanced Feature: Selecting Multiple Columns

Looking for an open-source Angular library that can display items in multiple columns rather than each item spanning across multiple columns. Many libraries support tabular display, but the challenge is to find one that arranges items in multiple columns. ...

Creating mesmerizing noise animation using THREE.FilmPass() in Three.js

Chapter Eleven of my Learning Three.js book showcases a fascinating noise animation created by the author using var effectFilm = new THREE.FilmPass(0.8, 0.325, 256, false); In the code example from the book, it is interesting to note that removing the orb ...

Having trouble converting a JSON array into a JavaScript array upon creation

I have encountered this question multiple times before and despite trying various solutions, I have not been able to find success. Summary: My goal is to retrieve the array from the classes.json file and then assign the data in the variable classes from d ...

Using AngularJS to load a custom JavaScript file within an ng-view

In my sample project, I have utilized Angular Js for the front-end. I have developed a template and implemented dynamic loading of views based on requirements. For this application, I am utilizing angular, jquery, and cusotm js. The structure of my templat ...

Decode JSON and generate a user-friendly Array

My aim is to extract and organize the JSON data received from an external API into a custom array. However, I am encountering two challenges: I'm struggling to access the value labeled #2 under "Meta Data". If I want to extract the first array n ...

Creating a Clickable SVG Element in React

I've been attempting to set up an onClick event in React, specifically within an SVG that includes multiple circle objects. However, when using "onClick," I'm encountering a strange issue: Upon data load, the onClick event is triggered six times ...

The protractor-jasmine2-html-reporter fails to generate an HTML report

In my protractor config.js, I have set up the configuration to generate screenshots in a specific folder, but the HTML report is not being generated. I have followed the steps mentioned in this guide: https://www.npmjs.com/package/protractor-jasmine2-htm ...

Rewrite: "Rewriting URL POST requests in Node.js

Within my JavaScript file, I have this function: exports.authentication = function(req, res) { // .. // user validation // .. res.redirect('/login'); }; I'm looking to modify all POST requests to a different path, such as / ...

Collapse or expand nested rows within a dynamic table using Bootstrap Collapse feature

I am currently working on creating a dynamic leaderboard table for a sports league using data from a SQL database. The league consists of multiple teams, each team has different players (with some players belonging to more than one team), and players earn ...

Choose with text partially aligned on the right side

Is there a way to align a portion of the option's text to the right? Below, you will see a select element with names on the left and "(vertical)" on the right. I want to move "(vertical)" to the right side. Is it possible to achieve this? https://i. ...