How to Control YouTube’s Video Player with JavaScript

Progress Bar

This is done using the player.seekTo(sec) function, which jumps the video to the seconds provided in the parameter.

To demonstrate this we’ve made our own version of YouTube’s progress bar, using an input field of type range. When we click anywhere on it, we take the inputs value, witch gives us a percentage. We then use this percentage to calculate what progress we want made to the video and skip to the according seconds.

$('#progress-bar').on('mouseup touchend', function (e) {

    // Calculate the new time for the video.
    // new time in seconds = total duration in seconds * ( value of range input / 100 )
    var newTime = player.getDuration() * (e.target.value / 100);

    // Skip video to new time.
    player.seekTo(newTime);

});

Play and Pause Buttons for YouTube and Vimeo Videos (via Their APIs)

The Vimeo player API actually works by sending commands through <span style="color: #2e2f3e;">postMessage</span> right to the iframe. You don’t need the froogaloop library to do that, but <span style="color: #2e2f3e;">postMessage</span> has some inherent complexities that this library (by Vimeo themselves) makes way easier. Plus it’s only 1.8kb so I’d recommend it.


						

How to Control YouTube’s Video Player with JavaScript

  • Player Initialization

    <span class="hljs-keyword">var</span> player;
    
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onYouTubeIframeAPIReady</span>() </span>{
        player = <span class="hljs-keyword">new</span> YT.Player(<span class="hljs-string">'video-placeholder'</span>, {
            width: <span class="hljs-number">600</span>,
            height: <span class="hljs-number">400</span>,
            videoId: <span class="hljs-string">'Xa0Q0J5tOP0'</span>,
            playerVars: {
                color: <span class="hljs-string">'white'</span>,
                playlist: <span class="hljs-string">'taJ60kskkns,FG0fTKAqZ5g'</span>
            },
            events: {
                onReady: initialize
            }
        });
    }
    
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">initialize</span>()</span>{
    
        <span class="hljs-comment">// Update the controls on load</span>
        updateTimerDisplay();
        updateProgressBar();
    
        <span class="hljs-comment">// Clear any old interval.</span>
        clearInterval(time_update_interval);
    
        <span class="hljs-comment">// Start interval to update elapsed time display and</span>
        <span class="hljs-comment">// the elapsed part of the progress bar every second.</span>
        time_update_interval = setInterval(<span class="hljs-function"><span class="hljs-keyword">function</span> () </span>{
            updateTimerDisplay();
            updateProgressBar();
        }, <span class="hljs-number">1000</span>)
    
    }
  • Duration

    0:16 / 4:50

    <span class="hljs-comment">// This function is called by initialize()</span>
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateTimerDisplay</span>()</span>{
        <span class="hljs-comment">// Update current time text display.</span>
        $(<span class="hljs-string">'#current-time'</span>).text(formatTime( player.getCurrentTime() ));
        $(<span class="hljs-string">'#duration'</span>).text(formatTime( player.getDuration() ));
    }
    
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">formatTime</span>(<span class="hljs-params">time</span>)</span>{
        time = <span class="hljs-built_in">Math</span>.round(time);
    
        <span class="hljs-keyword">var</span> minutes = <span class="hljs-built_in">Math</span>.floor(time / <span class="hljs-number">60</span>),
        seconds = time - minutes * <span class="hljs-number">60</span>;
    
        seconds = seconds < <span class="hljs-number">10</span> ? <span class="hljs-string">'0'</span> + seconds : seconds;
    
        <span class="hljs-keyword">return</span> minutes + <span class="hljs-string">":"</span> + seconds;
    }
    • Play

      play_arrow

      $(<span class="hljs-string">'#play'</span>).on(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> () </span>{
      
          player.playVideo();
      
      });
    • Pause

      pause

      $(<span class="hljs-string">'#pause'</span>).on(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> () </span>{
      
          player.pauseVideo();
      
      });