Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Javascript IFrame YouTube API Example to Embed Video With Advanced Controls in Browser

Posted on December 25, 2022

 

 

Welcome folks today in this blog post we will be using the iframe youtube api to embed videos with advanced controls in browser using javascript. All the full source code of the application is shown below.

 

 

Get Started

 

 

In order to get started you need to make an index.html file and copy paste the following code

 

 

index.html

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!DOCTYPE HTML>
<html>
 
<head>
    <title>Youtube Iframe Embed API</title>
</head>
<body>
    <form id="form">
        <input type="url" id="url" placeholder="Enter Youtube Video URL" required>
        <button>Embed Video</button>
    </form>
    <!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
    <div id="player-container" class="center">
        <div id="player"></div><br>
    </div>
    <input id="YouTube-player-progress" type="range" value="0" min="0" max="100"
        onchange="youTubePlayerCurrentTimeChange(this.value);" oninput="youTubePlayerCurrentTimeSlide();">
    <label for="YouTube-player-progress">duration</label>
    </div>
    <div>
        <input id="YouTube-player-volume" type="range" value="50" min="0" max="100"
            onchange="youTubePlayerVolumeChange(this.value);">
        <label for="YouTube-player-volume">volume</label>
 
        <button onclick="pauseVideo()" class="pauseButton">Pause</button>
        <button onclick="playVideo()" class="playButton">Play</button>
 
</body>
<script src="https://www.youtube.com/iframe_api"></script>
<script src="script.js"></script>
</html>

 

 

As you can see we are importing the youtube iframe api cdn link at the very bottom and then inside the html we have the simple html5 form where we have the simple input field in which the user will enter the youtube video url to embed it. And then we have the simple button to submit the form. And then we have the simple container where we will be embeding the youtube video And then we have two input range fields specifically for controlling the volume of the video and also controlling the time of the video. And then we have three buttons for start stop and pause the video.

 

 

 

And now we need to create the script.js file and copy paste the javascript code which is required for this application

 

 

script.js

 

 

First of all we will be writing the event and methods which will automatically execute when the iframe api is loaded inside the browser. In these methods we will be initializing the video player and then setting the videoid of the youtube video to embed as shown below

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
let player
 
function onYouTubeIframeAPIReady() {
  player = new YT.Player("player", {
    height: 500,
    width: 900,
    videoId: "8KrO5akeQgI",
    playerVars: {
      playsinline: 1,
      autoplay: 0,
      controls: 1,
    },
    events: {
      onReady: onPlayerReady,
      onStateChange: onPlayerStateChange,
    },
  });
}
 
function onPlayerReady() {
  console.log(true);
}
 
var done = false;
function onPlayerStateChange(event) {
  if (event.data == YT.PlayerState.PLAYING && !done) {
    done = true;
  }
}

 

 

As you can see we are attaching the youtube iframe api methods which automatically fires when the library is loaded. And here we are passing the static video id of the video that we want to load inside the browser when we load the page for the very first time

 

 

 

 

Adding the Controls to Video

 

 

Now we will be writing the javascript code for adding different controls to the video such as starting the video and pausing the video and also changing the volume and changing the time in the video

 

 

JavaScript
1
2
3
4
5
6
function pauseVideo() {
  player.pauseVideo();
}
function playVideo() {
  player.playVideo();
}

 

 

As you can see we are calling simple startVideo() and pauseVideo() methods on the player object to start and pause the video.

 

 

JavaScript
1
2
3
function youTubePlayerVolumeChange(volume) {
        player.setVolume(volume);
}

 

 

As you can see we are using the setVolume() method to change the volume of the video. Here we are receiving the volume from the input field where we attached the onchange event.

 

 

1
2
3
4
5
6
7
8
9
10
11
function youTubePlayerCurrentTimeChange(currentTime) {
 
    player.currentTimeSliding = false;
    player.seekTo(currentTime*player.getDuration()/100, true);
    
}
 
function youTubePlayerCurrentTimeSlide() {
 
    player.currentTimeSliding = true;
}

 

 

Here in the above code we are writing the two functions which is responsible for changing the time inside the video. We are using the seekTo() method to change the timestamp of the video to the currentTime which is received inside the function.

 

 

Loading the Dynamic Video From HTML5 Form

 

 

Now guys we will be getting the user submitted youtube video url and then extracting the videoid from the url and then we will be embeding the youtube video inside the browser.

 

 

1
2
3
4
5
6
7
8
9
let form = document.getElementById("form");
 
form.addEventListener("submit", (e) => {
  e.preventDefault();
  url = document.getElementById("url").value;
  console.log(url);
  videoId = YouTubeGetID(url);
  youTubePlayerChangeVideoId(videoId);
});

 

 

Now we will be defining the methods to extract the videoid from the youtube video url and also changing the video using the videoid

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function YouTubeGetID(url) {
  var ID = "";
  url = url
    .replace(/(>|<)/gi, "")
    .split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
  if (url[2] !== undefined) {
    ID = url[2].split(/[^0-9a-z_\-]/i);
    ID = ID[0];
  } else {
    ID = url;
  }
  return ID;
}
 
function youTubePlayerChangeVideoId(videoId) {
  player.cueVideoById({ suggestedQuality: "tiny", videoId: videoId });
  player.pauseVideo();
}

 

 

Full Source Code

 

 

script.js

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
var player;
 
let form = document.getElementById("form");
 
form.addEventListener("submit", (e) => {
  e.preventDefault();
  url = document.getElementById("url").value;
  console.log(url);
  videoId = YouTubeGetID(url);
  youTubePlayerChangeVideoId(videoId);
});
 
function youTubePlayerCurrentTimeChange(currentTime) {
 
    player.currentTimeSliding = false;
        player.seekTo(currentTime*player.getDuration()/100, true);
    
}
 
function youTubePlayerVolumeChange(volume) {
        player.setVolume(volume);
}
 
function youTubePlayerCurrentTimeSlide() {
 
    player.currentTimeSliding = true;
}
 
function pauseVideo() {
  player.pauseVideo();
}
function playVideo() {
  player.playVideo();
}
 
function YouTubeGetID(url) {
  var ID = "";
  url = url
    .replace(/(>|<)/gi, "")
    .split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
  if (url[2] !== undefined) {
    ID = url[2].split(/[^0-9a-z_\-]/i);
    ID = ID[0];
  } else {
    ID = url;
  }
  return ID;
}
 
function youTubePlayerChangeVideoId(videoId) {
  player.cueVideoById({ suggestedQuality: "tiny", videoId: videoId });
  player.pauseVideo();
}
 
function onYouTubeIframeAPIReady() {
  player = new YT.Player("player", {
    height: 500,
    width: 900,
    videoId: "8KrO5akeQgI",
    playerVars: {
      playsinline: 1,
      autoplay: 0,
      controls: 1,
    },
    events: {
      onReady: onPlayerReady,
      onStateChange: onPlayerStateChange,
    },
  });
}
 
function onPlayerReady() {
  console.log(true);
}
 
var done = false;
function onPlayerStateChange(event) {
  if (event.data == YT.PlayerState.PLAYING && !done) {
    done = true;
  }
}

 

 

Recent Posts

  • Angular 14/15 JWT Login & Registration Auth System in Node.js & Express Using MongoDB in Browser
  • Build a JWT Login & Registration Auth System in Node.js & Express Using MongoDB in Browser
  • React-Admin Example to Create CRUD REST API Using JSON-Server Library in Browser Using Javascript
  • Javascript Papaparse Example to Parse CSV Files and Export to JSON File and Download it as Attachment
  • Javascript Select2.js Example to Display Single & Multi-Select Dropdown & Fetch Remote Data Using Ajax in Dropdown
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme