JSFiddle - React, Tailwind, and code Playground
by naryad
HTML
<a href="javascript:void callPlayer("whateverID","playVideo")">Start</a> • <a href="javascript:void callPlayer("whateverID","pauseVideo")">Pause</a> • <a href="javascript:void callPlayer("whateverID","stopVideo")">Stop</a> - Hover over the links to see the called function
<br />
<div id="whateverID"><iframe width="640" height="390" frameborder="0" title="YouTube video player" type="text/html" src="http://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1"></iframe></div>
JavaScript
/*
* @param String frame_id The id of the div containing the frame
* @param String func Desired function to call, eg. "playVideo"
* @param Array args (optional) List of arguments to pass to function func*/
function callPlayer(frame_id, func, args){
/*func: playVideo, pauseVideo, stopVideo, ... Full list at:
* http://code.google.com/apis/youtube/js_api_reference.html#Overview */
if(!document.getElementById(frame_id)) return;
args = args || [];
/*Searches the document for the IFRAME with id=frame_id*/
var all_iframes = document.getElementsByTagName("iframe");
for(var i=0, len=all_iframes.length; i<len; i++){
if(all_iframes[i].parentNode.id == frame_id){
/*The index of the IFRAME element equals the index of the iframe in
the frames object (<frame> . */
window.frames[i].postMessage(JSON.stringify({
"event": "command",
"func": func,
"args": args,
"id": 1/*Can be omitted.*/
}), "*");
}
}
}
window.onload = function(){
callPlayer("whateverID", "playVideo");
}