DEV Community

Cover image for How to Create a video player with video.js
Gabriel Alao
Gabriel Alao

Posted on

How to Create a video player with video.js

  • Add the Video.js library to your HTML file. You can download the library from the Video.js website or use a content delivery network (CDN) link.
<head>
  <link href="https://vjs.zencdn.net/7.14.3/video-js.css" rel="stylesheet" />
  <script src="https://vjs.zencdn.net/7.14.3/video.js"></script>
</head>
Enter fullscreen mode Exit fullscreen mode
  • Add a video element to your HTML file and give it an ID. You can also specify the video file to play, along with any other options you want to set.

<body>
  <video id="my-video" class="video-js vjs-default-skin" controls preload="auto" width="640" height="360">
    <source src="my-video.mp4" type="video/mp4" />
    <p class="vjs-no-js">
      To view this video please enable JavaScript, and consider upgrading to a web browser that
      <a href="https://videojs.com/html5-video-support/" target="_blank">supports HTML5 video</a>
    </p>
  </video>
</body>
Enter fullscreen mode Exit fullscreen mode
  • Initialize the video player with JavaScript by passing the ID of the video element to the videojs function. You can also specify any additional options you want to set, such as autoplay or custom controls.
var player = videojs('my-video', {
  autoplay: true,
  controls: true,
  fluid: true
});
Enter fullscreen mode Exit fullscreen mode
  • You can now use the player variable to control the video playback, change the video source, add event listeners, and more.
// Play the video
player.play();

// Pause the video
player.pause();

// Change the video source
player.src('new-video.mp4');

// Listen for when the video has finished playing
player.on('ended', function() {
  console.log('The video has ended');
});
Enter fullscreen mode Exit fullscreen mode

These are the basic steps to create a video player with Video.js. You can customize the player's appearance and behavior using CSS and JavaScript, and add additional features like captions, ads, and plugins. The Video.js documentation provides more detailed information on how to use and customize the player.

Top comments (0)