Search code examples
javascripthtmlvimeo-api

Vimeo video with a custom unmute button using a video tag


Currently I'm autoplaying a video on page load from a Vimeo direct link with am html5 <video> tag, this loads the video really quick on the page and the poster attribute also helps for perceived loading time:

<video id="video" poster="abc.jpeg?$staticlink$" playsinline muted>
      <source type="video/mp4" src="https://player.vimeo.com/external/408636.hd.mp4?s=1552e499fb1e3aa2bf881c2ae762aa23988b5d&profile_id=175">
</video>

Now I want a way to unmute this using a button on the page, I've decided to do this i have to now use the Vimeo API player.js. See code below. The problem I'm having now is the iframe loads slow, and the vimeo API doesnt seem to have a poster attribute.

  <html>
    <div id="video" width="100%" height="100%"></div>
    <button class="volume">VOLUME ON</button>
  </html>

  <script>
    var volBtn = document.querySelector('.volume')

    var options = {
      url: "https://vimeo.com/123/456",
      loop: true,
      autoplay: true,
      background: true
    };

    var videoPlayer = new Vimeo.Player('video', options);

    volBtn.addEventListener('click', () => {
      videoPlayer.setVolume(1);
    })
  </script>

Is there a better way to do this, so we have both the video tags speed, and the iframes ability to unmute? Am I missing something obvious with the video or iframe tags? Can I maybe use a video tag with the Vimeo API?


Solution

  • No need to use player.js for this. It's as simple as:

    const volBtn = document.querySelector('.volume')
    const video = document.querySelector('#video')
    volBtn.addEventListener('click', function() { videoEl.muted = false })
    

    Also note that setting volume on a muted video with the help of HTMLMediaElement API leaves it muted. So this

    volBtn.addEventListener('click', function() { videoEl.volume = 1 })
    

    won't work as you expect. But this will

    volBtn.addEventListener('click', function() {
     videoEl.muted = false
     videoEl.volume = 1
    })