The YouTube video continues to play even after the container is closed

I recently worked on implementing a lightbox feature using jQuery, where a window opens upon clicking an element. Everything was working fine with images, but when I tried to open a YouTube video and play it, the video kept playing in the background even after closing the window (through display:none). I followed this tutorial for setting up the lightbox. The YouTube video was embedded as an iframe.

To close the window:


$(".js-modal-close, .modal-overlay").click(function() {
$(".modal-box, .modal-overlay").fadeOut(500, function() {
$(".modal-overlay").remove();
});
});

Can anyone suggest a solution to fix this issue?

Answer №1

Step 1: To start, enable the iframe API by adding enablejsapi=1 to the iframe URL and assigning an id to the iframe element:

<iframe id="video-player" src="https://www.youtube.com/embed/MxMBueIjtv0?enablejsapi=1" frameborder="0" allowfullscreen></iframe>

Step 2: Next, load the API script and create a player using the id specified in step 1. In this example, we used video-player:

var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;
function onYouTubeIframeAPIReady() {
  /* Additional actions can be taken on the 'onReady' event, 
     but for the purpose of this demo, it's not necessary.
     The video should be ready by the time you close the modal. */
  player = new YT.Player('video-player');
}

Step 3: Lastly, utilize the stopVideo function in your close modal snippet:

$(".js-modal-close, .modal-overlay").click(function() {
  player.stopVideo(); /* Optionally, you can set the video to start at 0 with `player.seekTo(0);` */
  $(".modal-box, .modal-overlay").fadeOut(500, function() {
    $(".modal-overlay").remove();
  });
});

More information: https://developers.google.com/youtube/iframe_api_reference
Demo: http://jsfiddle.net/4f5dksj5/

Answer №2

React Solution


interface VideoProps {
  videoId: string;
}

function EmbeddedYoutubeVideo (props:VideoProps) {
  const { videoId } = props;

  const pauseVideo = () => {
    // You can also use 'stopVideo' or 'playVideo' instead of pauseVideo
    var iframe = document.querySelector("iframe");
    iframe?.contentWindow?.postMessage(
      '{"event":"command","func":"pauseVideo","args":""}',
      "*"
    );
  };

  const handleCloseButtonClick = () => {
    pauseVideo();
    setShowVideoModal(false);
  };

return(
  <iframe
    src={`https://www.youtube-nocookie.com/embed/${videoId}?enablejsapi=1`}
    title="YouTube video player"
    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
    allowFullScreen={true}
    frameBorder={0}
  />

  <button
    onClick={handleCloseButtonClick}
  />
)}

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

Is it unorthodox to utilize constructor instances as prototypes in "WebGL - Up and Running"?

In the book "WebGL - Up and Running," a unique custom geometry is created in a rather straightforward manner. However, what caught my attention was the penultimate line of code. Here's how it looked: Saturn.Rings = function ( innerRadius, outerRadius ...

Improving the efficiency of your if else code in React js

I am looking for a way to optimize my code using a switch statement instead of multiple if-else conditions. How can I achieve this? Here is the current version of my code: handleChange = (selectedkey) => { this.setState({ activeKey: selectedkey } ...

Implementing jquery-confirm in CodeIgniter: A Step-by-Step Guide

I'm having some trouble with the jquery-confirm plugin from . Everything seems to be working fine, but when I try to delete an item, the jquery pops up an alert. However, when I click "okay", it doesn't actually delete the item. I can't figu ...

Enhance Your Website with Dynamic Navigation Animation

Seeking assistance with animating a navigation bar on and off the screen from the left side. The nav is not animating as expected using the latest version of jquery.min.js. The first step was to animate the nav upon clicking an object. View the current pro ...

A step-by-step guide on leveraging useRef() to specifically target dynamic material-ui tabs

When attempting to upload files to a specific channel, they always end up being uploaded to the first tab or channel. I've been using useRef to try and fix this issue, but I'm not sure what exactly is missing. By "tab," I am referring to the tab ...

Intermittent issue with Webdriver executeScript failing to detect dynamically created elements

It has taken me quite a while to come to terms with this, and I am still facing difficulties. My goal is to access dynamically generated elements on a web page using JavaScript injection through Selenium WebDriver. For instance: String hasclass = js.exec ...

I am experiencing an issue with using double quotation marks in VS Code

Whenever I press the double quote symbol like this "", the cursor automatically moves to the end. While this may be natural, I would prefer the cursor to move inside the double quotes automatically when pressing them. Additionally, it's a bi ...

Algorithm for searching and calculating with multiple words (Angular/Javascript)

As I work on loading a JSON file from the database containing two fields - words and grade, I face a challenge. Each word in the file is assigned a grade, for example, "true" has a grade of 1 while "lie" has a grade of -1. My goal is to take input from a t ...

Change the class of multiple elements using jQuery with a set time interval

Here is a clever jQuery snippet I've put together to toggle the class of an element at intervals: setInterval(function(){$('.grid-item .slide-image').toggleClass('active')}, 800); The code runs smoothly! However, I now have multi ...

Clicking through the button inside Vuetify's text-field append slot

While working on creating Vuetify's v-text-field with a slot named append containing a button, everything seems to be functioning correctly except for the fact that when I click the button, it goes through and focuses on the text field. On mobile devi ...

Sorting through an array using a different array of values

Looking to filter one array with another, where values in the first array should match 'id' in the second array for filtering. The arrays in question are: const array1 = [a, b, c, d] The array to be filtered based on matching 'id' va ...

Redux Persist causes the redux state to become undefined

I recently added redux-persist to my project and now I am facing an issue where all of my Redux states are returning undefined. Previously, all the Redux states were functioning properly. However, after incorporating redux-persist, they are no longer work ...

Issue with Click event not functioning properly following an ajax request in a dynamic element within the Backbone framework

I have successfully implemented a dynamic popup in my Backbone.view through the click of a button: var Section = Backbone.View.extend({ className: 'sqs-frontend-overlay-editor-widget-section', events:{ 'click .sqs--section--control__ed ...

Creating responsive images in Bootstrap columns

I've found a solution to my issue with large images, but I am still struggling with smaller images not fitting well into larger spaces. Essentially, I created a CMS for a user who required templates with various bootstrap columns as content areas. Cu ...

Ways to activate onChange multiple times for a single item within material ui's autocomplete feature

I am utilizing the autocomplete component in the Material UI. Upon selecting an item, the onChange props are triggered and certain actions are performed. However, I am encountering an issue where I can select the same object multiple times without the on ...

updating the background image in CSS after uploading a photo using Ajax

Whenever I click on an element, it triggers an input dialog that allows me to upload a photo. The server then responds with a JSON OBJECT containing 4 items: NAME, TYPE, HEIGHT, WIDTH. My goal is to refresh the element's background with the newly upl ...

Extracting Ajax responses and storing them as variables in JavaScript

Currently, I am developing a small PHP script and using the following code for an ajax query: var CODE = $('.code').val(); var CASE = $('.code').attr('case'); $.ajax({ type:'POST', ...

Discovering the most recent Node.js version: A step-by-step guide

Is it possible to check the latest available Nodejs version using npm? While node -v allows us to see the current version, I am curious if there is a way to access the most recent version through JavaScript. For example, process.version can be used to vi ...

Tips for arranging Radio buttons in multiple columns within the same Radio group in Material UI

As a newcomer in the world of React.js, I am feeling a bit anxious about posting my question on Stack Overflow. I hope everyone can overlook my lack of experience and forgive me for any mistakes. I have been struggling to find the right solution to my prob ...

After signing out, the function getRedirectResult in Firebase is being invoked

I'm a bit confused about some interesting behavior I've noticed while working with Firebase. Although I never used the older version, I believe getRedirectResult is a newer feature since they partnered with Google. Currently, I am using Vue.js a ...