0

There are several YouTube iframes that are being embedded on one HTML page. The task is to pause those videos when the user clicks on specific links/buttons. I have implemented it this way, but Firefox and IE doesn't seem to take it into consideration. I have spent quite some time googling around, haven't found any better approaches. Would be glad if you could suggest ways to refactor the code and make it work in all major browsers (and IE9+).

videos = (function() {
  var
    players = [],
    pauseMatchers = ".close-overlay, .owl-next, .owl-prev, a.btn-contact";

  var bind = function(e) {
    var pauseButtons = $(pauseMatchers);

    pauseButtons.each(function(index, el) {
      $(el).on("click", function() {
        pauseAll();
      });
    });
  };

  var push = function(object) {
    players.push(object);
  };

  var pauseAll = function() {
    $(players).each(function(index, el) {
      el.pauseVideo();
    });
  };

  return {
    bind: bind,
    push: push,
    players: players
  };
})();

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

function onYouTubeIframeAPIReady() {
  $("[data-behaviour~=embed]").each(function(index, el) {
    var player, $el = $(el);

    player = new YT.Player($el.attr("id"), {
      events: {
        "onReady": videos.bind
      }
    });

    videos.push(player);
  });
}

Here is the fiddle.

Adam
  • 101
  • 1
  • 7
  • Could you add a fiddle please? – user2718671 Apr 09 '14 at 14:28
  • @user2718671, added the fiddle link to the question. – Adam Apr 09 '14 at 15:36
  • 1
    Sorry, I tried but I couldn't find a solution. It's strange. Both players are selected and only one stops. For the second the stop function is not defined. Maybe you could try something with http://stackoverflow.com/questions/6671232/youtube-api-stop-video the callplayer and select by id function – user2718671 Apr 10 '14 at 08:59
  • @user2718671, yeah, the behaviour is quite odd, I will try the callplayer with object embedding, thanks! – Adam Apr 10 '14 at 10:12

0 Answers0