Youtube Iframe Javascript API part1

Hey guys,

In this tutorial, we will discuss how to load YouTube video with help of YouTube JavaScript API. YouTube provides us a simple JavaScript API to load particular YouTube API. All we need one div and section, YouTube JavaScript API library and some JavaScript functions. But If you want to control some YouTube video operations like play the video with html button, pause the video with html button, stop the video, mute or unmute etc. Then you need to use some YouTube JavaScript API library functions. First we need to create one player object with help onYouTubeIframeAPIReady function, before that we need to load //www.youtube.com/iframe_api/ youtube iframe api.   onYouTubeIframeAPIReady function will create player object with YT.Player class.

Youtube iframe js api

Live Demo 

If you look the above code I provided some meta information like height of player, width, video id(you need to pass the id of video what you want to play), some player variables and event functions like onPlayerReady : this event function will be called when the player ready. onPlayerStateChange: this event function will be called when state of player will be changed like play, pause or End.

When you load index page, one video also loads automatically because of one default attribute data-play-video,  if you like to load other video then add data-play-video=’1’ to video button

 

If you add data-play-video=’1’ more than one video button then it will load first one.

Here are some variables which will be use in functions

var player;  this variable will be used as global object of player.

 var tag = document.createElement(‘script’); To create script tag by javacript.

tag.src = “//www.youtube.com/iframe_api/”; source of js iframe api

var pre_video = “”;  This variable will be used to check user clicked on same video id or different.

var current_obj; To create current button object so we can perform several operations with same meta values.

$video_id = “”; Set video id to this variable and use in several functions.

Now here are some more functions to pause the video, mute the video or unmute the video, load other video by click on play button.

  1. Play the video by the click play button

  1. Pause the video:

  1. Mute the video

  1. Player state change function

  1. Common function which will be called whenever player state will change

This function will be called when user pause / play the video by player controls or play / pause by html button.

About jayant

jayant

Related posts: