cferdinandi / tabby

Lightweight, accessible vanilla JS toggle tabs.
MIT License
599 stars 73 forks source link

Stop video from playing when tab is inactive #8

Closed cferdinandi closed 8 years ago

cferdinandi commented 10 years ago

Added in version 5.3

elalemanyo commented 8 years ago

Hi, The way you stop the videos is making them reload it again when the user get back to the tab. I have a small js to pause the video on tab change event, is it possible to make stopVideos a setting?

Thanks!

cferdinandi commented 8 years ago

@elalemanyo It's possible, but I'm not sure it's worth the extra conditional to do so. Would you mind sharing your code so I can see what you're doing?

Worth mentioning, the reload only happens with iFrames. HTML5 video is paused using the video API.

elalemanyo commented 8 years ago

I have some youtube iframe and I also have some other iframes. All the time was reloading all of them, when user change the tab, that was really annoying.

Also I had a small code to pause youtube videos, using youtube API.

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 players = {};
window.onYouTubePlayerAPIReady = function() {
  $('.tabs-content #videos').controlYTiframes();

  $('.tabs-content #videos').on('activeTab', function() {
    $.each(players, function(index, val) {
      stopVideo(index);
    });
   });
};

$.fn.controlYTiframes = function() {
  $(this).find('iframe').each(function (k, v) {
    players[v.id] = new YT.Player(v.id, {
      events: {
        'onStateChange': onPlayerStateChange
      }
    });
  });
}

function onPlayerStateChange(event) {
  if (event.data == YT.PlayerState.PLAYING) {
    stopVideo(event.target.a.id);
  }
}

function stopVideo(player_id) {
  $.each(players, function(index, val) {
    if (val.getIframe().id != player_id && val.getPlayerState() == 1) {
      val.pauseVideo();
    }
  });
}

Not sure if the code can help someone... it is project specific. I pause the videos from same tab, and I pause all of them when user change tab.

cferdinandi commented 8 years ago

Looking at this documentation, I think you're right about making this an option.

I'll add an option to disable stopVideo and run your own stuff via a callback if desired. Reopening this ticket.

cferdinandi commented 8 years ago

Added with v10.1.0 https://github.com/cferdinandi/tabby/pull/61