I have this script that I need as a .js file, so I can use it multiple times without having multiple copies of the script everywhere, like calliing the script YTiFramePlayer.js. But, maybe I want to change promoVideo, or videoId. How would I do that?
//YouTube iframe player
//Load the iframe Player API
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('promoVideo', {
height: '390',
width: '640',
videoId: '00000',
events: {
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.STOPPED) {
stopVideo();
}
}
function startVideo() {
$("#video").css("height", "calc(100vh - 48px)");
player.playVideo();
}
function stopVideo() {
player.stopVideo();
$("#video").css("height", "0px");
}
You can save this as a .js file as mentioned previously, but wrap the functionality in a global variable that you can access elsewhere. Example:
script.js:
//YouTube iframe player
//Load the iframe Player API
var ytPlayer = (function() {
var tag = document.createElement('script');
var videoId;
var promoVideo = 'promoVideo';
var player;
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
return {
init(id, promoVideo) {
videoId = id;
promoVideo = promoVideo;
onYouTubeIframeAPIReady();
}
}
function onYouTubeIframeAPIReady() {
console.log('Setting up:', videoId, promoVideo)
player = new YT.Player(promoVideo, {
height: '390',
width: '640',
videoId: videoId,
events: {
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.STOPPED) {
stopVideo();
}
}
function startVideo() {
$("#video").css("height", "calc(100vh - 48px)");
player.playVideo();
}
function stopVideo() {
player.stopVideo();
$("#video").css("height", "0px");
}
})();
HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<h1>Hello Plunker!</h1>
<script>
ytPlayer.init('a8a83sda', 'someOtherId')
</script>
</body>
</html>
See the revealing module pattern for more information.
just save as with filename.js extension
Related
Im trying force autoplay when the youtube video is ready.
<html>
<body>
<div id="player"></div>
<br/>
<button id="botaoPlay" onclick="playMusic()">play</button>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
var timeout = null;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '360',
width: '640',
videoId: '8t3EHHhkC34',
playerVars: { autoplay: 1 , enablejsapi: 1, playsinline: 1, origin: 'http://localhost' },
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange,
'onError': onPlayerError
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.setVolume(65);
if(!timeout)
timeout = setInterval(playMusic, 1000);
}
function playMusic() {
if (player) {
player.playVideo();
}
}
function onPlayerStateChange(event) {
console.log("status changed: " + player.getPlayerState());
if( player.getPlayerState() == 1 ){
clearInterval(timeout);
}
}
</script>
</body>
</html>
But the video only starts if i click on button... how can i start the video? I tried instead call playVideo() in interval, call button.click() but didnt work too, only if i click with mouse in button. How can i start my video without click on button?
Somewhat related to:
YouTube IFrame API doesn't always load?
But different in that I AM loading the YouTube script per instructions. Note, in my source, the iframe is ABOVE the script block in the load order. I based this off of these instructions (below). The example works fine if I'm on that page, but doesn't seem to work for me when I put the code on mine. I'm sure I'm missing something really simple but I'm to be missing it. Thanks!
https://developers.google.com/youtube/iframe_api_reference#Mobile_considerations
var tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
//Console shows this script is loading
var player;
function onYouTubeIframeAPIReady() {
console.log("onYouTubeIframeAPIReady", arguments); //This shows in console
player = new YT.Player('js_youTubeFrame', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
console.log("onPlayerReady",event); //Never triggers
}
function onPlayerStateChange(event) {
console.log("onPlayerStateChange", event); //Never triggers
if (event.data === YT.PlayerState.PLAYING) {
console.log("YouTube Video is PLAYING!!"); //Never triggers
}
}
<div id="js_youTubeContainer" class="embed-responsive embed-responsive-16by9">
<iframe id="js_youTubeFrame" class="embed-responsive-item" src="https://www.youtube-nocookie.com/embed/u3A7bmEOtaU?enablejsapi=1&rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
</div>
Best way to load a Youtube Video by his API, is following this sintaxis:
<div id="video-youtube"></div>
<script id="youtube-tracking-script">
var youtubeVideoId = 'u3A7bmEOtaU'; // replace with your own video id
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementById("youtube-tracking-script");
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var video;
function onYouTubeIframeAPIReady() {
video = new YT.Player('video-youtube', {
height: '352',
width: '100%',
videoId: youtubeVideoId,
playerVars: {rel: 0, showinfo: 0},
events: {
'onStateChange': videoPlay
}
});
}
function videoPlay(event) {
if (event.data == YT.PlayerState.PLAYING) {
console.log("YouTube Video is PLAYING!!");
}
if (event.data == YT.PlayerState.PAUSED) {
console.log("YouTube Video is PAUSED!!");
}
if (event.data == YT.PlayerState.ENDED) {
console.log("YouTube Video is ENDING!!");
}
}
</script>
https://jsfiddle.net/t4qwfk0d/1/
You should replace your <iframe> </iframe> to <div id= "js_youTubeFrame"> </div>, in my case it works.
I think that Youtube Iframe Api needs that div to convert it on iframe after.
I have an embedded YouTube videos in my HTML page. I'm trying to get the current time of YouTube video. I used the answer of that question to create page like this
(YouTube currentTime with jQuery)
When I'm trying to display the time I'm getting an error: 'getCurrentTime is not a function'.
HTML
<div style="text-align:center">
<button onclick="playPause()">Play</button>
<button onclick="showTime()">Show Time</button>
<br><br>
<iframe id = "it" width="560" height="315" src="https://www.youtube.com/v/FHtvDA0W34I?version=3&enablejsapi=1" frameborder="0" allowfullscreen></iframe>
<br>
<label id=startHighlighlbl>VideoHighlightStart: </label>
</div>
JavaScript
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
function ShowTime() {
alert(player.getCurrentTime());
}
</script>
You should load your video through the YT-API, so player is initialized correctly and thus accessible through the API. Basically you need to remove your iframe from your HTML and instead let YT-API create the iframe for you.
Try the following:
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('it', {
height: '315',
width: '560',
videoId: 'FHtvDA0W34I',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
function ShowTime() {
alert(player.getCurrentTime());
}
<body>
<button onclick="ShowTime()">Show Time</button>
<br>
<div id="it"></div>
</body
I've got a site with an HTML5 audio player and embedded YouTube music videos. I'd like to make it so that when the user clicks on a YouTube video to play it the music will stop. Wrapping the iframe in
<div id='vidWrapper' onclick='pauseAudio()'>YT stuff</div>
works for the sliver of pixels outside of the iframe, but not when you click on the actual video. Anyone have any ideas?
You should use the YouTube IFrame API. Add an event listener for onStateChange to get notified when the player's state changes. See the sample code below.
<!DOCTYPE html>
<html>
<head>
<script src="https://www.youtube.com/iframe_api"></script>
</head>
<body>
<div id='vidWrapper'>
<!-- The <iframe> (and video player) will replace this <div> tag. -->
<div id="ytplayer"></div>
</div>
<script>
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('ytplayer', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onStateChange': function(event) {
if (event.data == YT.PlayerState.PLAYING) {
pauseAudio();
}
}
}
});
}
function pauseAudio() {
...
}
</script>
</body>
</html>
//More Refined Way to answer this question would be --
//HTML code----
<!DOCTYPE html>
<html>
<body>
<div id='vidWrapper'>
//your iframe tag goes here.
<iframe id="video-id-first" src="https://www.youtube.com/embed/nNlEiuqiKAk?enablejsapi=1&origin=http%3A%2F%2F3.7.232.244" gesture="media" allow="encrypted-media" allowfullscreen="" data-gtm-yt-inspected-53610233_3="true" width="560" height="400" frameborder="0"></iframe>
</div>
</body>
</html>
//JS code ----
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
var width = document.getElementById("video-id-first").getAttribute("width");
var height = document.getElementById("video-id-first").getAttribute("height");
var src = document.getElementById("video-id-first").getAttribute("src");
//splitting to get the videoId from src.
var partsArr = src.split("/");
var videoSource = partsArr[partsArr.length -1 ].split("?");
var videoId = videoSource[videoSource.length -2 ];
function onYouTubeIframeAPIReady() {
player = new YT.Player('vidWrapper', {
height:height,
width: width,
videoId: videoId,
events: {
'onStateChange': function(event) {
if (event.data == YT.PlayerState.PLAYING) {
startVideo();
}
if (event.data == YT.PlayerState.PAUSED) {
stopVideo();
}
}
}
});
}
function startVideo() {
//write your functionality here.
alert('Video Started');
}
function stopVideo() {
//write your functionality here.
alert('Video Paused');
}
<div id=player></div>
<div id=playvideo style= "width:40px; height:80px; background-color:#2b2b2b;" >
<script src="https://apis.google.com/js/platform.js"></script>
<script type="text/javascript">
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '448',
width: '763',
playerVars: {
'showinfo': 0,
'controls': 0,
listType: 'playlist',
list: 'PLD7SqVUGDdDBw_xmMKTDF5MlBwys_KlUk'
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
// event.target.playVideo();
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
player.stopVideo();
}
}
</script>
I have an embed code like that, and I want the div named "playvideo" acts like YouTube's play button, I think it's an easy one but I'm new on JavaScript, can anybody have an idea?
Well you can use YouTube's Player API function:
player.playVideo()
So ... HTML:
<div id="mydiv" onclick="play_this_video()">Play my video</div>
and JavaScript:
function play_this_video(){
player.playVideo();
}