jQuery - Tab with videos... how do I get videos to stop playing when I switch between tabs?
Solution 1
This should work:
I simply put all your URL's in an array. When the user decides to leave the tab, I clear the src
of the iframe
so that the video "stops" playing.
The first time your currentTab
variable is still empty though, so I retrieve it by looking at which <li>
has its class set to active
. From this <li>
I take the link and set the currentTab
variable to its href
.
if (currentTab == '') {
//Find current tab:
currentTab = $('#tabs ul li.active').find('a').attr('href');
}
//Stop playing video:
if (currentTab != '')
$('div#' + currentTab).find('iframe').attr('src', '');
When he gets back to any tab, you should not forget to set the src
back though, else your iFrame will be empty. It's what I do here:
var index = $(this).attr('id');
$('div#' + currentTab).find('iframe').attr('src', urls[index]);
This code can still be optimized though to reduce the flickering. An easy way to do this is by setting a function on the load
trigger of the iframe
's. This way you know when the video has been successfully set and it is then that you want to show the tab to the user.
Solution 2
Without using any special targeting of iframe or video ids, here's how I stop any playing movie when selecting a different tab. Uses the native bootstrap tab events:
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var iframe = $(e.relatedTarget.hash).find('iframe');
var src = iframe.attr('src');
iframe.attr('src', '');
iframe.attr('src', src);
s});
Ori
Updated on June 05, 2022Comments
-
Ori almost 2 years
I am new to jQuery, and I managed to create a tab interface. I want each section of my tab to have a YouTube video. However, when I click play on the video that is on tab 1 for example, and then switch to tab 2, the video on tab 1 still keeps on playing. Please see the entire code here:
I would greatly appreciate any help on how to stop the video once the user clicks on other tabs.
Also, when I run this on my Android, flash enabled phone, the videos don't seem to play. Any idea of what I need to do to fix? Or do I need to fix anything else to make code browser compatible?