HowToGaming
HowToGaming

Reputation: 124

How to pause Vimeo video in Javascript?

I'm gonna make this as short as possible so that I can get a quick fix.

I have a lightbox that opens up with a vimeo video. There is a button in the top right of the screen to remove the lightbox, however the vimeo video still plays in the background and you can hear it, whilst not seeing it. I need to be able to pause the vimeo video while also hiding the lightbox.

Here is the code I have so far:

 var lightbox = 
        '<div id="lightbox">' +
        '<a><p id="click-to-close">Click to close</p></a>' +
        '<div id="content">' + //insert clicked link's href into img src
          ' <iframe id="video" src="https://player.vimeo.com/video/131429700?autoplay=1&title=0&byline=0&portrait=0?api=1" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>' +
        '</div>' +  
      '</div>';



  $("#click-to-close").click(function() {
   $('#lightbox').hide();

          var iframe = document.getElementById('video');

// $f == Froogaloop
var player = $f(iframe);


var pauseButton = document.getElementById("click-to-close");
pauseButton.addEventListener("click", function() {
  player.api("pause");
});
     
    
  
  });

Is there anything that I am missing/doing wrong?

Upvotes: 4

Views: 13648

Answers (1)

Kaiido
Kaiido

Reputation: 137133

You are adding an eventListener in the click handler which will hide your button.

var lightbox =
  '<div id="lightbox">' +
  '<a><p id="click-to-close">Click to close</p></a>' +
  '<div id="content">' +
  ' <iframe id="video" src="https://player.vimeo.com/video/131429700?autoplay=1&title=0&byline=0&portrait=0?api=1" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>' +
  '</div>' +
  '</div>';



$("#click-to-close").click(function() {
  // here you hide the pauseButton's container
  $('#lightbox').hide();

  var iframe = document.getElementById('video');
  // $f == Froogaloop
  var player = $f(iframe);

  var pauseButton = document.getElementById("click-to-close");
  // it is now hidden, we can't access it anymore...
  pauseButton.addEventListener("click", function() {
    player.api("pause");
  });
});

So you have two solutions :

  • append your button outside the #lightbox element, which seems odd, since the hidden video will still be playing,
  • directly call player.api("pause"); in the first click handler

.

$("#click-to-close").click(function() {
  $('#lightbox').hide();
  var iframe = document.getElementById('video');
  // $f == Froogaloop
  var player = $f(iframe);
  player.api("pause");
});

Upvotes: 4

Related Questions